Click here to Skip to main content
15,885,366 members
Articles / Database Development / SQL Server / SQL Server 2008

Inside Recursive CTEs

Rate me:
Please Sign up or sign in to vote.
4.46/5 (7 votes)
25 May 2010CPOL5 min read 49.3K   185   11  
A step by step explanation of how a recursive CTE actually works.
-- setup a simple table to query ********************
declare @t table (
	Id int,
	ParentId int	
)
insert @t(Id, ParentId)
values (1, 0), (2, 1), (3, 1), (4, 2), (5, 4), (6, 3)



-- the recursive query ******************************
;with cte as (
	select	1 id, 0 ParentId
	union all
	select	C.Id, C.ParentId
	from	@t as C
			inner join cte P on C.ParentId = P.Id	
)
select * from cte


-- doing the same thing by hand *********************
declare @cte table (
	id int,
	ParentId int,
	Pass int
)
declare @Pass int
set		@Pass = 0

insert	@cte(id, ParentId, Pass)
values	(1, 0, @Pass)

while	 @@ROWCOUNT > 0
begin
	-- increment pass
	set @Pass = @Pass + 1
	
	-- insert next set
	insert	@cte (id, ParentId, Pass)
	select	C.Id, C.ParentId, @Pass
	from	@t C
			inner join @cte P 
				on C.ParentId = P.id
				and P.Pass = @Pass - 1 -- only look at rows from the previous pass
end	
select * from @cte


-- simulating the pass in the CTE *********************
;with cte as (
	select	1 id, 0 ParentId, 0 Pass -- start with Pass = 0
	union all
	select	C.Id, 
			C.ParentId, 
			P.Pass + 1	-- Increment Pass column with each pass by adding 1 to the previous value (note that *P*.Pass was used to add to)
	from	@t as C
			inner join cte P on C.ParentId = P.Id	
)
select * from cte

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Leaseplan Corporation
Netherlands Netherlands
Gert-Jan is a Senior Quantitative Risk Manager at Leaseplan Corporation. In that job he doesn't get to code much he does these little projects to keep his skills up and feed the inner geek.

Comments and Discussions