Returning the parent/ child relationship on a self-joining table

前端 未结 1 1720
感情败类
感情败类 2021-01-26 23:30

I need to be able to return a list of all children given a parent Id at all levels using SQL.

The table looks something like this:

ID   ParentId   Name
-         


        
1条回答
  •  被撕碎了的回忆
    2021-01-27 00:11

    To get all children for a given @ParentId stored in that manner you could use a recursive CTE.

    declare @ParentId int
    --set @ParentId = 1
    
    ;WITH T AS
    (
    select 1 AS ID,null AS ParentId, 'Root' as [Name] union all
    select 2,1,'Child of Root' union all
    select 3,2,'Child of Child of Root'
    ),
    cte AS
    (
    SELECT ID, ParentId, Name
    FROM T 
    WHERE ParentId = @ParentId  OR (ParentId IS NULL AND @ParentId IS NULL)
    UNION ALL
    SELECT T.ID, T.ParentId, T.Name
    FROM T 
    JOIN cte c ON c.ID = T.ParentId
    )
    SELECT ID, ParentId, Name
    FROM cte
    OPTION (MAXRECURSION 0)
    

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