Different result with * and explicit list of fields?

I was studying another question when I hit this behavior on 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 will 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 missing something?

Here is 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)
+3
source share
2 answers

Edit

I think I know what is happening, and is a great example of why, in order to avoid a choice * in the first place.

First you defined a table with childId, then parentId, but CTE Foo expects parentId, then childId,

, , # bar. * childId, parentId, parentId, child. n-, .

, SQL.

: * .

+5

, , , , , . select * , . SQL Server 2008 : Msg 205, 16, 1, 1 , UNION, INTERSECT EXCEPT, .

, , .

* - , , .

-1

Source: https://habr.com/ru/post/1707774/


All Articles