【问题标题】:Returning the parent/ child relationship on a self-joining table返回自联接表上的父/子关系
【发布时间】:2010-09-06 16:01:57
【问题描述】:
我需要能够使用 SQL 返回所有给定父级 ID 的所有子级的列表。
表格看起来像这样:
ID ParentId Name
---------------------------------------
1 null Root
2 1 Child of Root
3 2 Child of Child of Root
给出一个 '1' 的 ID,我将如何返回整个列表...?嵌套的深度也没有限制...
谢谢,
基隆
【问题讨论】:
标签:
tsql
sql-server-2008
hierarchy
【解决方案1】:
要让给定@ParentId 的所有子代以这种方式存储,您可以使用递归 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)