如何在不使用 CTE 的情况下从日期范围创建日期列表 [英] How to create a list of dates from a daterange without using a CTE
本文介绍了如何在不使用 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
这篇关于如何在不使用 CTE 的情况下从日期范围创建日期列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文