Pages

Friday 11 January 2013

Hierarchical table sorting with a parent Child relation

declare @tbl_accounts table (AccountID int, name varchar(50), ParentID int)

insert into @tbl_accounts select 1,'Alex',0
insert into @tbl_accounts select 2,'John',1
insert into @tbl_accounts select 3,'Mathew',2
insert into @tbl_accounts select 4,'Philip',1
insert into @tbl_accounts select 5,'Shone',0
insert into @tbl_accounts select 6,'Shine',2
insert into @tbl_accounts select 7,'Tom',2
insert into @tbl_accounts select 8,'George',1
insert into @tbl_accounts select 9,'Jim',5


;with cte as
(
select 
    Accountid, 
    name, 
    parentid, 
    cast(row_number()over(partition by parentid order by name) as varchar(max)) as [path]
from @tbl_accounts
where parentid = 0
union all
select
    t.AccountID,
    t.name,
    t.ParentID,
    [path] + cast(row_number()over(partition by t.parentid order by t.name) as varchar(max))
from
    cte
join @tbl_accounts t on cte.AccountID = t.ParentID
)

select  
    Accountid,
    name,
    ParentID,
    [path]
from cte 
order by path
 
 
1    Alex    0    1
8    George    1    11
2    John    1    12
3    Mathew    2    121
6    Shine    2    122
7    Tom    2    123
4    Philip    1    13
5    Shone    0    2
9    Jim    5    21

No comments:

Post a Comment