I was exploring another question, when I hit this behaviour in Sql Server 2005. This query would exhaust the maximum recursion:
with foo(parent_id,child_id) as (
select parent_id,child_id
from #bar where parent_id in (1,3)
union all
select #bar.* -- Line that changed
from #bar
join foo on #bar.parent_id = foo.child_id
)
select * from foo
But this would work fine:
with foo(parent_id,child_id) as (
select parent_id,child_id
from #bar where parent_id in (1,3)
union all
select #bar.parent_id, #bar.child_id -- Line that changed
from #bar
join foo on #bar.parent_id = foo.child_id
)
select * from foo
Is this a bug in Sql Server, or am I overlooking something?
Here's the table definition:
if object_id('tempdb..#bar') is not null
drop table #bar
create table #bar (
child_id int,
parent_id int
)
insert into #bar (parent_id,child_id) values (1,2)
insert into #bar (parent_id,child_id) values (1,5)
insert into #bar (parent_id,child_id) values (2,3)
insert into #bar (parent_id,child_id) values (2,6)
insert into #bar (parent_id,child_id) values (6,4)