如何从开始和结束日期生成格式化的周字符串

时间:2011-06-28 16:35:13

标签: sql tsql sql-server-2008

是否可以生成这样的集合:

April 1 2010  
April 8 2010  
April 15 2010  
April 22 2010  
April 29 2010  
May 6 2010  

等等。

从仅使用SQL的开始日期和结束日期开始?

1 个答案:

答案 0 :(得分:3)

你可以通过CTE递减:

declare @start datetime = '1 apr 2010'
declare @end   datetime = '6 may 2010'

;with weeks(wdate) as
(
    select @start as wdate

    union all

    select 
        dateadd(week, 1, wdate)
    from weeks
        where wdate < @end
)
select wdate
    from weeks 

2010-04-01 00:00:00.000
2010-04-08 00:00:00.000
2010-04-15 00:00:00.000
2010-04-22 00:00:00.000
2010-04-29 00:00:00.000
2010-05-06 00:00:00.000