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

一笑奈何 提交于 2019-12-04 05:29:07

问题


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    null       Root
2    1          Child of Root
3    2          Child of Child of Root

Give an Id of '1', how would I return the entire list...? There is no limitation on the depth of the nesting either...

Thanks,
Kieron


回答1:


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)


来源:https://stackoverflow.com/questions/3652788/returning-the-parent-child-relationship-on-a-self-joining-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!