Get all parents for a child

后端 未结 3 1375
春和景丽
春和景丽 2020-12-14 16:50

I want to retrieve the parentid of an id, if that parentid has a parent again retrieve it, and so on. Kind of hierarchy table.

id----parentid
1-----1
5-----1         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-14 17:12

    you didn't mention the desired output and input. However you can try like this,

    Declare @t table (id int ,parentid int)
    insert into @t
    select 1,1 union all
    select 5,1 union all
    select 47894,5 union all
    select 47897,47894 
    
    ;With CTE as
    (
    select * from @t where id=1
    union all
    Select a.* from @t a inner join cte b
     on b.id=a.parentid and
    a.id<>b.id
    )
    select * from cte
    

提交回复
热议问题