使用背景
一般项目中会遇到,求每日的日报这种,以及计算2个日期内的工作日,或者休息日可能会用到,计算休息日可以用额外的一个字段用来标记当前日期是否是休息日
遍历方式一
DECLARE @StartDate DATE = '2023-01-01', @EndDate DATE = '2023-12-31';DECLARE @interval int= datediff (day,@StartDate,@EndDate)
SELECT DATEADD(DAY,number,@StartDate) Daily FROM master..spt_values WHERE type = 'P' AND number >= 0 AND number<=@interval
遍历方式二
DECLARE @StartDate DATE = '2023-01-01', @EndDate DATE = '2023-12-31';
WITH DateSequence AS
(SELECT @StartDate AS DateValueUNION ALLSELECT DATEADD(day, 1, DateValue)FROM DateSequenceWHERE DATEADD(day, 1, DateValue) <= @EndDate
)
SELECT DateValue
FROM DateSequence
OPTION (MAXRECURSION 0); -- 移除递归限制