Sql Server CTE Parent Child recursive

后端 未结 1 1708
情话喂你
情话喂你 2021-01-25 08:17

I have following table structure:

create table Test(
  ParentId int,
  ChildId int
 )

insert into Test(ParentId, ChildId)
select 1, NULL
union
select 1, 2
union         


        
相关标签:
1条回答
  • 2021-01-25 08:19

    As #Mikael Eriksson said: "You have a circular references in your data. 5 is parent to 6 and 6 is parent to 5."

    Also in recursive part you output ParentId from previous step, not from just found rows.

    declare @Test table (ParentId int, ChildId int)
    
    insert into @Test (ParentId, ChildId)
    select 1, null
    union all
    select 1, 2
    union all
    select 1, 3
    union all
    select 2, null
    union all
    select 2, 5
    union all
    select 5, 6
    union all
    --select 6, 5
    --union all
    select 6, 8
    
    declare @id int = 2
    
    ;with MyCTE as (
        select ParentId, ChildId
        from @test
        where ParentId = @id
    
        union all
    
        select t2.ParentId, t2.ChildId
        from MyCTE t1
        inner join @Test t2 on t1.ChildId = t2.ParentId
    )
    
    select * from MyCTE
    

    Another thing I didn't understand is why do you have such rows where ChildId is null and ParentId is not null. How can it be possible?

    Does it mean that you have unknown items whose parent is known?

    0 讨论(0)
提交回复
热议问题