【发布时间】:2020-09-10 10:47:41
【问题描述】:
我有以下从源到目标的分层数据,我想在出现对现有源的引用时停止
create table #temp (source int, destination int);
insert into #temp values (1,3), (3,7), (7,9), (9,1);
WITH cte (Source, Destination, Level, Sources)
AS
(
SELECT Source, Destination, 0 AS Level, CAST(Source AS VARCHAR(MAX)) + ',' AS Sources
FROM #temp
WHERE [Source] = 1
UNION ALL
SELECT t.[Source], t.Destination, cte.[Level] + 1, cte.Sources + CAST(t.Source AS VARCHAR(MAX)) + ','
FROM #temp t
INNER JOIN cte ON cte.Destination = t.[Source] AND (CAST(t.Destination AS VARCHAR(MAX)) + ',' NOT LIKE '%' + cte.Sources + '%')
)
select * from cte
drop table #temp;
但是,在运行此程序时,我仍然会遇到最大递归错误。我应该如何正确编写保护条款?我想要的是前 3 个结果。
【问题讨论】:
-
CTE 第二部分中的
where子句通常可以解决问题。where cte.[Level] < 2之类的东西(应该给出 3 个结果:级别 0、1 和 2)。
标签: sql-server common-table-expression infinite-loop