views:

32

answers:

2

Why this query is completed with error ?

;with tempData as
 (
        select 32 as col1, char(32) as col2
        union all
        select col1+1, char(col1+1) from tempData
 )
select * from tempData
A: 

You have an infinite loop: where should it end?

gbn
@gbn: You are right its infinit loop but i want to know how its loop because i dont know how 'With' works.
Jeevan Bhatt
+2  A: 

Recursion needs a terminating condition. For example

;with tempData as ( 
select 32 as col1, char(32) as col2 
union all 
select col1+1, char(col1+1) from tempData 
where col1 < 255
) 
select * from tempData
option (maxrecursion 223)

With regards to the question in the title about how it works internally see this answer.

Martin Smith
@Martin:- thanks for your answer its quit informative but now i want to know what is option(maxrecursion 0) ?
Jeevan Bhatt
@Jeevan - By default CTEs will stop recursion after 100 levels. `option(maxrecursion 0)` means that it will continue recursion indefinitely (for ever if you have an infinite loop - or at least until SSMS runs out of resources!).
Martin Smith
I got it, thanks Martin
Jeevan Bhatt