Hi everybody,
I could not figure out this problem - I need to show parents with their children ordered by RightsOrder
I could not figure out this problem - I need to show parents with their children ordered by RightsOrder
Code:
declare @Test table
(pk_rights Int, fk_rights int null, RightsName varchar(max), RightsOrder smallint, Description varchar(max))
insert into @test select
1, NULL, 'Open Category Library', 0, 'Open Category Library'
union select
18 , NULL, 'Open Portfolio Footnote Library', 1, 'Open Portfolio Footnote Library'
union select
2, 1, 'Add Category Library', 0, 'Add Category Library'
union select
3, 1, 'Delete Category Library', 1, 'Delete Category Library'
union select
11, 2, 'Edit Category Library', 0, 'Edit Category Library'
union select
7, 2, 'Add Category', 1, 'Add Category'
union select
12, 2, 'Add Category Language', 2, 'Add Category Language'
union select
14, 2, 'Add Category Caption', 3, 'Add Category Caption'
union select
9, 2, 'Delete Category', 4, 'Delete Category'
union select
16, 2, 'Delete Category Caption', 5, 'Delete Category Caption'
union select
17, 2, 'Delete Cateogry Language', 6, 'Delete Cateogry Language'
union select
8 ,7, 'Edit Category', 0, 'Edit Category'
union select
13, 12, 'Edit Category Lanaguage', 0, 'Edit Category Lanaguage'
union select
15 ,14 ,'EditCategory Caption', 0, 'EditCategory Caption'
select * from @Test
;with cte_t as (select T1.RightsName, T1.[Description], T1.pk_rights, T1.fk_rights, 0 as Level,
T2.RightsName as ChildName, T2.RightsOrder, T2.[Description] as ChildDescr
from @Test T1 inner join @test T2 on T1.pk_rights = T2.pk_rights where T1.fk_rights IS NULL
union all
select T1.RightsName, T1.[Description], T1.pk_rights, t1.fk_rights, Level + 1 as Level,
D2.ChildName, D2.RightsOrder, D2.[Description] as ChildDescr from @Test T1
inner join cte_t D on T1.fk_rights = D.pk_rights
)
select * from cte_t order by fk_rights, RightsOrder, Level