Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parent/Child hierarchy tree view

I have a parents table looks like this

CHILD_ID | PARENT_ID | NAME
1        | Null      | Bill
2        | 1         | Jane
3        | 1         | Steve
4        | 2         | Ben
5        | 3         | Andrew

Id like to get a result set like this

Bill
---Jane
------Ben
---Steve
------Andrew

I know I need to do a rank query to rank the levels and a self join but all I can find on the net is CTE recursion

I have done this in Oracle before but not in MS SQL

like image 896
Rob Avatar asked Dec 04 '22 17:12

Rob


1 Answers

Bit hacky and can be improved but hopefully it shows the principle...

;with relation (childId, parentId, childName, [level], [orderSequence])  
as  
(  
select childId, parentId, childName, 0, cast(childId as varchar(20))  
from @parents  
where parentId is null  
union all  
select p.childId, p.parentId, r.[level]+1, cast(r.orderSequence + '_' + cast(p.childId as varchar) as varchar(20))  
from @parents p  
inner join relation r on p.parentId = r.childId  
)  

select right('----------', ([level]*3)) +childName  
from relation  
order by orderSequence

If however you want to avoid recursion then an alternative approach is to implement a tree table with the relevant tree structure information - see http://www.sqlteam.com/article/more-trees-hierarchies-in-sql for a walk through

like image 161
kaj Avatar answered Jan 05 '23 05:01

kaj