【发布时间】:2015-11-24 19:29:53
【问题描述】:
我正在尝试构建一个 CTE,它将拉回与数据库中给定的任意记录相关的所有记录。
Create table Requests (
Id bigint,
OriginalId bigint NULL,
FollowupId bigint NULL
)
insert into Requests VALUES (1, null, 3)
insert into Requests VALUES (2, 1, 8)
insert into Requests VALUES (3, 1, 4)
insert into Requests VALUES (4, 3, null)
insert into Requests VALUES (5, null, null)
insert into Requests VALUES (6, null, 7)
insert into Requests VALUES (7, 6, null)
insert into Requests VALUES (8, 2, null)
OriginalId 始终是先前记录的Id(或null)。 FollowupId 指向最近的后续记录(反过来,通过 OriginalId 指向回来)并且可能会被忽略,但如果它有帮助,它就在那里。
我可以使用以下 CTE 轻松拉回给定记录的所有祖先或所有后代
;With TransactionList (Id, originalId, followupId, Steps)
AS
(
Select Id, originalId, followupId, 0 as Steps from requests where Id = @startId
union all
select reqs.Id, reqs.originalId, reqs.followupId, Steps + 1 from requests reqs
inner join TransactionList tl on tl.Id = reqs.originalId --or tl.originalId = reqs.Id
)
SELECT Id from TransactionList
但是,如果我同时使用两个 where 子句,我会遇到递归,达到递归限制,然后它就会崩溃。即使将这两组结合起来,我也没有得到整棵树——只有一个分支。
除了 ID 列表之外,我什么都不关心。他们不需要排序,也不需要显示他们的关系或任何东西。不疼,但没必要。但是我需要给定树中的每个Id 在它作为@startId 传递时拉回相同的列表。
作为我希望看到的示例,这是当 @startId 设置为任何值 1-4 或 8 时的输出:
1
2
3
4
8
对于 6 或 7,我会返回 6 和 7。
【问题讨论】:
-
你在这里并不陌生。一些ddl和样本数据怎么样?也许是 sqlfiddle.com?
-
@SeanLange - 我无法用小提琴来运行我的 CTE。但我已经在问题中添加了数据和预期结果。
标签: sql-server tree sql-server-2012 common-table-expression