【问题标题】:SQL Recursion CTE infinite loopSQL 递归 CTE 无限循环
【发布时间】:2020-02-08 03:08:48
【问题描述】:

我有这个例子,我看不懂,希望你能帮助我!

我有一个火车线路表,如下所示:

任务是从给定的开始(递归)获取每个可能的目的地。

我试过这样做:

    with cte (st, nd) as(
    select from1, to1
    from RailwayTbl
    where from1 = 'Berlin'

    union all

    select e.from1, e.to1
    from RailwayTbl e join cte
    on cte.nd = e.from1
    )
    select * from cte;

执行时出现如下错误:

语句终止。在语句完成之前,最大递归 100 已用完。 ((这是一个无限循环..))

当我删除 all 并使用 union 时,只有我得到了这个错误:

递归公用表表达式“cte”不包含顶级 UNION ALL 运算符。

有什么想法吗?? 提前致谢!

【问题讨论】:

  • MySQL SQL Server。你实际使用的是什么?这看起来像是 SQL Server 错误,而不是 MySQL。
  • 您的数据是图像,而不是text,因此我们无法测试,但看起来您有多个循环引用。例如'Amsterdam' -> 'Berlin' -> 'Amsterdam' -> 'Berlin' -> 'Amsterdam' .... -> 'Berlin' -> 'Amsterdam' ... -> 'Berlin' -> @ 987654335@...你明白了

标签: sql sql-server recursion common-table-expression


【解决方案1】:

您需要停止递归,这在 SQL Server 中是个难题。以下保留访问站的字符串以停止递归:

 with cte as (
       select from1 as st, to1 as nd, concat(',', st, ',', to1) as dests, 1 as lev
       from RailwayTbl
       where from1 = 'Berlin'
       union all
       select e.from1, e.to1, concat(cte.dests, e.to1, ',') as dests, lev + 1
       from RailwayTbl e join
            cte
            on cte.nd = e.from1
       where dests not like concat('%,', e.nd, ',%')
    )
select * from cte;

我还添加了lev。我经常在 cte 定义的递归部分使用where lev < 10 进行调试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2016-09-28
    • 2016-10-06
    • 1970-01-01
    • 2023-03-29
    • 2021-11-04
    • 2020-04-01
    相关资源
    最近更新 更多