SQL Server get parent list

后端 未结 2 877

I have a table like this:

id name parent_id
1  ab1  3
2  ab2  5
3  ab3  2
4  ab4  null
5  ab5  null
6  ab6  null

I need to do a query with

2条回答
  •  星月不相逢
    2021-01-07 02:43

    Something like this perhaps?

        WITH parents(id,name,parent,level)
        AS
        (
        SELECT
           ID,
           NAME,
           PARENT,
           0 as level
        FROM
           TABLE
        WHERE ID = 1
        UNION ALL
        SELECT
           ID,
           NAME,
           PARENT,
           Level + 1
        FROM 
           TABLE
        WHERE
           id = (SELECT TOP 1 parent FROM parents order by level desc)
        )
        SELECT * FROM parents
    

提交回复
热议问题