Last week I had a problem where I needed a hierarchical chain of results. I had to get results of all organisations above my organsiation in a hierarcy. I knew how I would do this by recursion in C#, but had no idea how to get it done in SQL. But asking a bit around, and searching the web I got a really nice solution using the to me new WITH-command. And it seems quite fast aswell. Here is a SQL script with some testdata:
Create table #Relations ( ID int PRIMARY KEY, ChildId int, name varchar(50) ) insert into #Relations values (5, 4, 'Me') insert into #Relations values (4, 3, 'Father') insert into #Relations values (3, 2, 'Grandpa') insert into #Relations values (2, 1, 'Great Grandpa') insert Into #Relations values (1, null, 'Great Old Grandpa') declare @startid int set @startid = 5 ;WITH Names AS ( --Gets the starting line SELECT * FROM #Relations where id = @startid UNION ALL SELECT r.* FROM #Relations r INNER JOIN names n ON n.ChildId=r.id ) select * from names
Here are the results. As you can see, it works;)
ID ChildId name---------- ----------- --------------------------------------------------5 4 Me4 3 Father3 2 Grandpa2 1 Great Grandpa1 NULL Great Old Grandpa(5 row(s) affected)
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.