这是我用来寻找解决方案的链接..
http://wiki.lessthandot.com/index.php/Using_Common_Table_Expressions_for_Parent-Child_Relationships
编辑 - @Pshimo - 谢谢。这是链接中的指南。
使用 SQL 2005 虽然这是一个梦想。假设您有以下示例数据:
declare @test table (bunchof uniqueidentifier default newid(), columns uniqueidentifier default newid(), Id int, ParentID int)
insert @test (Id, ParentId)
select 1, null
union all select 5, 1
union all select 15, 2
union all select 16, 5
union all select 27, 16
并且您想获取 1 的所有子行(因此 ItemId 5、16、27)
declare @parentId int
set @parentId = 1
;--last statement MUST be semicolon-terminated to use a CTE
with CTE (bunchof, columns, Id, ParentId) as
(
select bunchof, columns, Id, ParentId
from @test
where ParentId = @parentId
union all
select a.bunchof, a.columns, a.Id, a.ParentId
from @test as a
inner join CTE as b on a.ParentId = b.Id
)
select * from CTE
如果你想包括父母:
declare @Id int
set @Id = 1
;--last statement MUST be semicolon-terminated to use a CTE
with CTE (bunchof, columns, Id, ParentId) as
(
select bunchof, columns, Id, ParentId
from @test
where Id = @Id
union all
select a.bunchof, a.columns, a.Id, a.ParentId
from @test as a
inner join CTE as b on a.ParentId = b.Id
)
select * from CTE
如果您喜欢这种情况,您也可以在层次结构中选择深度:
declare @Id int
set @Id = 1
;--last statement MUST be semicolon-terminated to use a CTE
with CTE (bunchof, columns, Id, ParentId, Depth) as
(
select bunchof, columns, Id, ParentId, 0
from @test
where Id = @Id
union all
select a.bunchof, a.columns, a.Id, a.ParentId, b.Depth + 1
from @test as a
inner join CTE as b on a.ParentId = b.Id
)
select * from CTE
如您所见,您在这里所做的是首先选择您的初始记录集,其中包含父 ID 参数的所有子行。然后,您可以联合到另一个连接到 CTE 本身的查询,以获取孩子的孩子(和他们的孙辈,等等,直到您到达最后一个后代行。重要的是要注意默认递归限制为 100,所以请支付使用这些时要注意层次结构的深度。您可以使用 OPTION (MAXRECURSION) 更改递归限制
WITH CTE AS (
...
)
SELECT * FROM CTE OPTION (MAXRECURSION 1000)