gpt4 book ai didi

sql-server - X 次递归循环后停止查询

转载 作者:行者123 更新时间:2023-12-02 03:47:49 28 4
gpt4 key购买 nike

我有一个递归查询。仅当存在无限循环时,该查询在大多数情况下才有效,我想从数据库返回一些结果而不是

The maximum recursion 100 has been exhausted before statement completion.

查询如下:

WITH bom ( [id],[parentNumber],[warehouse],[sequenceNumber] 
,[childNumber],[childDescription],[qtyRequired],[childItemClass]
,[childItemType],[scrapFactor],[bubbleNumber] ,[operationNumber]
,[effectivityDate],[discontinuityDate],[companyID]) AS (
select * from [products].[BillOfMaterial] where parentNumber IN ('XXXXXXXXXX')
and companyID = '0'UNION ALL
select c.* from bom b INNER JOIN [products].[BillOfMaterial] c on b.childNumber = c.parentNumber and c.companyID = '0')
SELECT distinct * FROM bom

所以我想更改查询,以便可以解决上述问题并返回某些级别的数据。通常树的深度不会超过 5 层。

这在 Sql 服务器递归查询中可能吗?

最佳答案

我不认为有一个OPTION可以做你想要的事情,但是你可以创建一个变量来保存你希望递归发生的最大次数,并在查询:

Declare @MaxLevel Int = 5;

With bom (id, parentNumber, warehouse, sequenceNumber, childNumber, childDescription, qtyRequired, childItemClass, childItemType, scrapFactor, bubbleNumber,
operationNumber, effectivityDate, discontinuityDate, companyID, Level
)
As (Select *,
1 As Level
From products.BillOfMaterial
Where parentNumber In ( 'XXXXXXXXXX' )
And companyID = '0'
Union All
Select c.*,
Level + 1 As Level
From bom b
Inner Join products.BillOfMaterial c
On b.childNumber = c.parentNumber
And c.companyID = '0'
Where Level < @MaxLevel
)
Select Distinct *
From bom;

这是一个带有日期的工作示例:

Declare @MaxLevel Int = 5;

;With Cte As
(
Select Convert(Date, GetDate()) As Date,
1 As Level
Union All
Select DateAdd(Day, 1, Date) As Date,
Level + 1 As Level
From Cte
Where Level < @MaxLevel
)
Select *
From Cte

Results

Date        Level
2017-09-14 1
2017-09-15 2
2017-09-16 3
2017-09-17 4
2017-09-18 5

关于sql-server - X 次递归循环后停止查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46221118/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com