sql-server - T-SQL : simple recursion exceeding max recursion depth

标签 sql-server recursion exceed

我有一个表格my_table


rowNumber    number   ...
1               23
2               14
3               15
4               25
5               19
6               21
7               19
8               37
9               31
        ...
1000            28
我想找到number列的递增连续序列的最大长度。对于本示例,将为 3:

14, 15, 25

我的想法是计算每个数字的长度:


rowNumber    number   ...   length
1               23            1
2               14            1
3               15            2
4               25            3
5               19            1
6               21            2
7               19            1
8               37            2
9               31            1
        ...
然后取最大值。为了计算长度,我编写了以下使用递归的查询:

with enhanced_table as (select *
                               ,1 length
                       from    my_table 
                       where   rowNumber = 1
                       union all
                       (select b.*
                               ,case when b.number > a.number 
                                     then a.length + 1 
                                     end new_column
                       from    enhanced_table a, my_table b 
                       where   b.rowNumber = a.rowNumber + 1
                       )
select  max(length)
from    enhanced_table
因此,我尝试从 rowNumber = 1 开始,并通过递归连续添加所有其他行。我收到在语句完成之前最大递归 100 已耗尽错误。

我的问题是:我应该找到一种方法来增加服务器上允许的最大迭代次数(考虑到查询很简单,我认为运行 1000 次迭代不会有问题),还是找到另一种方法?

此外,100 次迭代的阈值是不是太低了?

谢谢!

最佳答案

必须有一些默认阈值,这就是 Microsoft 选择的。这是为了防止无限循环。此外,循环在 SQL Server 中表现不佳,并且违背了其基于集合的结构。

您可以指定要为单个查询设置的最大递归。这会覆盖默认值。

select  max(length)
from    enhanced_table
option (maxrecursion 1000)

注意,选项(maxrecursion 0)与无限制相同...并且可能导致无限循环

<强> REFERENCE

An incorrectly composed recursive CTE may cause an infinite loop. For example, if the recursive member query definition returns the same values for both the parent and child columns, an infinite loop is created. To prevent an infinite loop, you can limit the number of recursion levels allowed for a particular statement by using the MAXRECURSION hint and a value between 0 and 32,767 in the OPTION clause of the INSERT, UPDATE, DELETE, or SELECT statement. This lets you control the execution of the statement until you resolve the code problem that is creating the loop. The server-wide default is 100. When 0 is specified, no limit is applied. Only one MAXRECURSION value can be specified per statement

关于sql-server - T-SQL : simple recursion exceeding max recursion depth,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50914029/

相关文章:

java - 递归构造函数调用

algorithm - 动态算法查找数组中 "accessible"数字的乘积的最大和

sql - 如何正确应用递归CTE?

max - 有没有办法增加Solana链上程序构建的计算单元

c# - 使用具有单个 DbContext 和 Entites 的多个数据库并在运行时生成 Conn String

sql-server - Delphi 的多数据库访问

sql-server - 包含在 (@start, @end) VS BETWEEN - 时态表中

SQL 表锁定