递归CTE生成额外记录

时间:2016-05-01 06:31:06

标签: sql-server recursion

我有以下递归SQL查询来生成日期中提供的任何月份的所有日期。

它总是产生额外的日期(下个月1日)。

DECLARE @currentDate DATE = '2016-5-25';
WITH cte AS(
    SELECT DATEADD(DAY, -DATEPART(DAY, @currentDate) + 1, @currentDate) AS  firstDay
    UNION ALL
    SELECT DATEADD(DAY, 1, firstDay) 
    FROM cte
    WHERE DATEPART(MONTH, firstDay) = DATEPART(MONTH, @currentDate)
)
SELECT * FROM cte

我做错了什么?

1 个答案:

答案 0 :(得分:1)

Recursive CTE中,首先执行递归查询,然后验证Where子句

这是正确的方法

DECLARE @currentDate DATE = '2016-5-25';

;WITH cte AS(
    SELECT dateadd(dd,1,eomonth(@currentDate,-1)) AS  fd
    UNION ALL
    SELECT DATEADD(DAY, 1, fd) 
    FROM cte
    WHERE fd < eomonth(@currentDate)
)
SELECT * FROM cte

相反,您可以使用计数表来执行此操作,与Recursive CTE

相比,效果更好
;WITH e1(n) AS
(
    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), -- 10
e2(n) AS (SELECT 1 FROM e1 CROSS JOIN e1 AS b), -- 10*10
e3(n) AS (SELECT 1 FROM e1 CROSS JOIN e2), -- 10*100
tally as (SELECT id = ROW_NUMBER() OVER (ORDER BY n) FROM e3 )
select 
dateadd(DD,ID-1,dateadd(dd,1,eomonth(@currentDate,-1))) as Dates
from Tally
where dateadd(DD,ID-1,dateadd(dd,1,eomonth(@currentDate,-1)))<=eomonth(@currentDate)