SQL Server 递归自顶向下父级及其子级

vm0i2vca  于 2022-12-10  发布在  其他
关注(0)|答案(1)|浏览(133)
declare @table as table
 (
  Id int,
  ParentId int
 )

 insert into @table
 values (1 , null),(2,1),(3,1),(4,2),(5,2),(6,3),(7,3)

  ;with cte 
    as (select Id,ParentId,1 as [level]
        from @table as t 
        where ParentId is null
        UNION ALL
        select t.Id,t.ParentId , cte.level + 1
        from @table as t 
        join cte 
        on t.ParentId = cte.Id)
    select *
    from cte
IdParentIdLevel
1NULL1
212
312
633
733
423
523

I want to get Top to Bottom Parent -> it's all descendants
and again Top to Bottom Parent -> it's descendants
but I am unable to get expected output using above query
expected output vertically in table
Id 1 -> 2 -> 4 -> 5
Id 1 -> 3 -> 6 -> 7

expected output

IdParentIdLevel
1NULL1
212
423
523
1NULL1
312
633
733

A tree Starts from 1 and goes to bottom to find it's all child
1 -> 2 -> 4 -> 5
again tree Starts from 1 and goes to bottom to find it's all child
1 -> 3 -> 6 -> 7

jdgnovmf

jdgnovmf1#

declare @table as table
 (
  Id int,
  ParentId int
 )

 declare @cte as table
 (
  Id int,
  ParentId int 
 )

 declare @output as table
 (
  Id int,
  ParentId int
 
 )
  
 insert into @table
 values (1,null),(2,1),(3,1),(4,2),(5,2),(6,3),(7,3)

 declare @id int 
 declare @parentid int
  

  ;with cte 
    as (select Id,ParentId
        from @table as t 
        where ParentId is null
        UNION ALL
        select t.Id,t.ParentId 
        from @table as t 
        join cte 
        on t.ParentId = cte.Id)
     insert into @cte
    select *
    from cte  
     
     
     declare @start int = 1
     declare @end int = (select count(ParentId) from @cte where ParentId= (select Id from @cte where ParentId is null))

     while(@start <= @end)
     begin
     
     select top 1 @id = Id  ,@parentid=ParentId from @cte where ParentId = (select Id from @cte where ParentId is null) 

     if(@id > 0 )
     begin

     insert into @output
     select * from @cte where ParentId is null

     insert into @output values (@id,@parentid)
     delete from @cte where Id = @id and ParentId = @parentid  

     insert into @output
     select * from @cte where ParentId = @id

     delete from @cte where Id  in (select Id from @cte where ParentId = @id)

     end
      
     set @start+=1
     end

     select * from @output

**thank you guys for your help i figured it out by myself.**it would be nice if any of you guys improve my answer, it is not best solution but currently it is what it is

相关问题