SQL recursive query that gets all ancestors of an item

后端 未结 2 593
小蘑菇
小蘑菇 2020-12-07 20:53
ID       parent_id   name
---------------------
1        2            first 
2        4            second
3        3            third
4        5            fourth
5          


        
2条回答
  •  醉酒成梦
    2020-12-07 21:42

    You can use something like this:

    with parents as 
    (
      select ID, parent_ID
      from t
      where parent_ID is not null
      union all 
      select p.ID, t.parent_ID
      from parents p
        inner join t on p.parent_ID = t.ID
          and t.parent_ID is not null
          and t.ID <> t.parent_ID
    )
    select *
      , parents = '(' + stuff
        (
          (
            select ', ' + cast(p.parent_ID as varchar(100))
            from parents p 
            where t.ID = p.ID
            for xml path('')
          ), 1, 2, ''
        ) + ')'
    from t
    order by ID
    

    SQL Fiddle with demo.

    This combines two very common T-SQL techniques - using a CTE to get a hierarchy and using FOR XML PATH to get a CSV list.

提交回复
热议问题