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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With