Improve company productivity with a Business Account.Sign Up
-- create a test table
create table testcte(id int,name varchar(20),subid int)
insert testcte select
1,'Steve',3 union all select
2,'Margot',3 union all select
3,'Family',6 union all select
4,'Other Family',6 union all select
5,'Evert',4 union all select
6,'Department',7 union all select
7,'City',8 union all select
8,'State',9 union all select
-- create the test procedure
create proc usp_testcte @start int as
;with cte as (
-- the part before "union all" is called the anchor, it starts the recursion
select subid, path=convert(varchar(max),name) from testcte where id=@start
-- the part after "union all" is called the recursive part. In here, "cte" references
-- the result from the most recent iteration of the recursion (starts with the anchor)
-- as long as this query generates results, it will continue to run, using the
-- previous iteration as the "table" content of "cte" ("cte" being the name given to the
-- common table expresion as the first word after "with")
select t.subid, cte.path+'\'+t.name from cte
inner join testcte t on t.id=cte.subid)
-- outside the CTE block, you can access the built-up results by referring to "cte" as a table
-- MAX is used here to just the last row, which in this case will be the longest
select max(path) from cte
-- test it
exec usp_testcte 1
Open in new window
Are you ready to take your data science career to the next step, or break into data science? With Springboard’s Data Science Career Track, you’ll master data science topics, have personalized career guidance, weekly calls with a data science expert, and a job guarantee.
Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.
Have a better answer? Share it in a comment.
Please enter a first name
Please enter a last name
Must be at least 4 characters long.
Join and Comment
Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.