Skip to content

Instantly share code, notes, and snippets.

@pedroreys
Last active February 11, 2021 07:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pedroreys/8336d6f4dcb63ba619c0 to your computer and use it in GitHub Desktop.
Save pedroreys/8336d6f4dcb63ba619c0 to your computer and use it in GitHub Desktop.
SQL Server version of this recursive query example to traverse a tree depth-first http://jakub.fedyczak.net/post/postgresql-with-recursive-tree-traversing-example/
declare @empl table(name nvarchar(max) null, boss nvarchar(max) null);
insert into @empl values ('Paul',null);
insert into @empl values ('Luke','Paul');
insert into @empl values ('Kate','Paul');
insert into @empl values ('Marge','Kate');
insert into @empl values ('Edith','Kate');
insert into @empl values ('Pam','Kate');
insert into @empl values ('Carol','Luke');
insert into @empl values ('John','Luke');
insert into @empl values ('Jack','Carol');
insert into @empl values ('Alex','Carol');
with t(level,path,boss,name) as (
select 0,name,boss,name from @empl where boss is null
union all
select
level + 1,
path + ' > ' + e.name,
e.boss, e.name
from
@empl e
inner join t on e.boss = t.name
) select * from t order by path;
level path boss name
----------- -------------------------------- -------- ------
0 Paul NULL Paul
1 Paul > Kate Paul Kate
2 Paul > Kate > Edith Kate Edith
2 Paul > Kate > Marge Kate Marge
2 Paul > Kate > Pam Kate Pam
1 Paul > Luke Paul Luke
2 Paul > Luke > Carol Luke Carol
3 Paul > Luke > Carol > Alex Carol Alex
3 Paul > Luke > Carol > Jack Carol Jack
2 Paul > Luke > John Luke John
@vsanthosaraj
Copy link

Nice. ... Working fine ..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment