我正在尝试获取当前月和最后两个月之间的所有日期。
例如:今天10-01-2019
使用sql脚本,我将获得2018年10月1日至2019年1月31日之间的所有日期。
with cte as
(
select getdate() as n
union all
select dateadd(DAY,-1,n) from cte where month(dateadd(dd,-1,n)) < month(DATEADD(month, -3, getdate())) --and month(DATEADD(month, 0, getdate()))
union all
select dateadd(DAY,-1,n) from cte where month(dateadd(dd,-1,n)) > month(DATEADD(month, 0, getdate()))
)
select * from cte
我懂了
错误消息530,级别16,状态1,第1行
声明终止。在语句完成之前,最大递归100已用尽。
最佳答案
with cte as
(
select dateadd(month,1,dateadd(day, -1* day(getdate()) , cast(getdate() as date) ) ) n
union all
select dateadd(day,-1,n) from cte where month(n) + year(n) * 12 >= month(getdate()) + year(getdate()) * 12 -3
),
final as (select * from cte except select top 1 * from cte order by n)
select * from final order by n
OPTION (MAXRECURSION 1000)
或仅使用dateadd并避免除外
with cte as
(
select dateadd(day,-1,dateadd(month,1,dateadd(day, 1 - day(getdate()) , cast(getdate() as date)))) n
union all
select dateadd(day,-1,n) from cte where n > dateadd(month,-3,dateadd(day , 1 - day(getdate()),cast(getdate() as date)))
)
select * from cte order by n
OPTION (MAXRECURSION 1000)
关于sql - 如何获取当前月和最后两个月之间的所有日期,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54131120/