以下递归查询应选择当天后的四个星期五:
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已经用尽”错误。有任何想法吗?
答案 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)