如何在不使用 CTE 的情况下从日期范围创建日期列表
问题描述:
以下链接说明了如何将日期范围转换为日期列表.我使用了这种方法,它工作正常,但查询没有执行(我使用 Maxrecursion 0 来取消限制).
The following link explains how to turn a date range into a list of dates. I used this approach and it works fine but the query is not performing (I used Maxrecursion 0 to unlimit).
http://blog.justinstolle.com/sql-turn-a-date-range-into-a-list-of-dates/
是否有其他解决方案可以完成此操作?(使用子查询还是声明表?)
Is there any other solution to get this done? (using subquery or declare table?)
答
尝试
declare @datestart date = '2012-1-1', @dateend date = '2012-10-31'
declare @days int = datediff(d,@datestart,@dateend)
select
dateadd(d, number, @datestart)
from master..spt_values
where type='p'
and number<=@days
如果您的日期范围超过 2047 天,您可以通过自行加入表格来延长它 - 以下将允许您最多 27 年..
If your date range is more than 2047 days, you can extend it by self joining the table - the below will allow you up to 27 years..
select
dateadd(d, v1.number+v2.number*2048, @datestart)
from master..spt_values v1
cross join (select number from master..spt_values where number<5 and type='p') v2
where type='p'
and (v1.number+v2.number*2048)<=@days