TRANSACT SQL:“max recursion exhausted”错误,但递归查询的结果很好

时间:2016-09-06 22:42:48

标签: sql sql-server recursion

以下递归查询应选择当天后的四个星期五:

 DECLARE @friday date
 DECLARE @today date

 Set @friday = '2016-09-02'
 Set @today = convert (date, getdate())

 While (datediff(dd, @Friday, @today) % 7) != 0
 BEGIN
 Set @today = DATEADD (dd, 1, @today) 
 END;

 With FourFridays (Friday) as (
 Select @today
 union all
 select DATEADD(DD, 7, Friday)
 FROM FourFridays
 )

 Select * from FourFridays 
 OPTION(MAXRECURSION 3)

结果我看起来很好,但我在SQL Server Management Studio中得到“语句完成前最大递归3已经用尽”错误。有任何想法吗?

1 个答案:

答案 0 :(得分:0)

要预测递归会导致的位置没有maxrecursion错误:

DECLARE @friday date
 DECLARE @today date

 Set @friday = '2016-09-02'
 Set @today = convert (date, getdate())

 While (datediff(dd, @Friday, @today) % 7) != 0
 BEGIN
 Set @today = DATEADD (dd, 1, @today) 
 END;

 With FourFridays (Friday, Recursion) as (
 Select @today, 1
 union all
 select DATEADD(DD, 7, Friday), Recursion + 1
 FROM FourFridays
 where  Recursion < 10
 )

 Select * from FourFridays 
 --OPTION(MAXRECURSION 3)