我正在尝试查找两个给定日期之间一周中某一天的所有实例。一周中的某一天可以改变。我在这里发布了类似的问题,但它似乎不适用于变量
SET DATEFIRST 1;
DECLARE @earliestStartDate DATETIME = '2016-08-01 00:00:00.000';
DECLARE @latestStartDate DATETIME = '2016-09-30 00:00:00.000';
DECLARE @weeklyCoursesStartDay INT = 1;
DECLARE @maxCourses INT = 30;
CREATE TABLE #Dates(CourseDate DATETIME);
WITH CTE(dt)
AS
(SELECT @earliestStartDate
UNION ALL
SELECT DATEADD(day, @weeklyCoursesStartDay, dt) FROM CTE--SELECT DATEADD(day, @weeklyCoursesStartDay, dt) FROM CTE
WHERE dt < @latestStartDate)
INSERT INTO #Dates(CourseDate)
SELECT TOP(@maxCourses) dt
FROM CTE
WHERE DATEPART(DW, dt) = @weeklyCoursesStartDay
OPTION (MAXRECURSION 0);
SELECT * FROM #Dates
DROP TABLE #Dates
按预期返回以下内容。
2016-08-01 00:00:00.000
2016-08-08 00:00:00.000
2016-08-15 00:00:00.000
2016-08-22 00:00:00.000
2016-08-29 00:00:00.000
2016-09-05 00:00:00.000
2016-09-12 00:00:00.000
2016-09-19 00:00:00.000
2016-09-26 00:00:00.000
但是当@weeklyCourseStartDay更改为5(表示星期五)时,它只返回两个结果:
2016-08-26 00:00:00.000
2016-09-30 00:00:00.000
答案 0 :(得分:1)
该行
SELECT DATEADD(day, @weeklyCoursesStartDay, dt) FROM CTE
实际应该是:
SELECT DATEADD(day, 1, dt) FROM CTE
这意味着递归CTE将在@earliestStartDate
和@latestStartDate
之间每天生成,并且在稍后阶段,WHERE DATEPART(DW, dt) = @weeklyCoursesStartDay
子句将确保只剩下正确工作日的日子。