如何在SQL Server 2008中

时间:2017-10-09 16:39:08

标签: sql-server

我将为我的存储过程获得的输入是开始日期和结束日期,因此根据这些日期,我需要日期范围之间的月份以及这些月份的开始和结束日期。

示例:

@StartDate  DATETIME = '20161125', @EndDate    DATETIME = '20170220';

@StartDate  DATETIME = '20161125',   
@EndDate    DATETIME = '20170220';

我基本上需要创建的是具有以下结果的CTE或临时表:

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以使用以下查询

declare @StartDate  date = '20161125', @EndDate    date = '20170220';

with cte as (
    select startDate = @StartDate,
           endDate = @EndDate,
           month=format(@StartDate,'MMM-yy'),  
           monthStart=@StartDate , 
           monthEnd =EOMONTH(@StartDate,0)
    union all
    select  @StartDate, 
            @EndDate,
            format(dateadd(day,1,monthEnd),'MMM-yy'),
            dateadd(day,1,monthEnd),
            iif(eomonth(dateadd(day,1,monthEnd),0)>@EndDate,
                  @EndDate,eomonth(dateadd(day,1,monthEnd),0))
    from cte
    where monthEnd<@EndDate
)
select * from cte

请注意:函数EOMONTH可以在sql-server 2012及以上版本中使用

编辑版本,未使用iifformateomonth函数

declare @StartDate  datetime = '20161125', 
        @EndDate    datetime = '20170220';

with cte as (
    select startDate = @StartDate,
           endDate = @EndDate,
           month=Left(DATENAME(MONTH, @StartDate),3) + '-' + Right(DATENAME(YEAR, @StartDate),2),  
           monthStart=@StartDate , 
           monthEnd =dateadd(month,datediff(month,0,@StartDate)+1,0)-1
    union all
    select  @StartDate, 
            @EndDate,
            Left(DATENAME(MONTH, dateadd(day,1,monthEnd)),3) + '-' + Right(DATENAME(YEAR, dateadd(day,1,monthEnd)),2),
            dateadd(day,1,monthEnd),
            case when  dateadd(month,datediff(month,0,dateadd(day,1,monthEnd))+1,0)-1 > @EndDate 
                 then @EndDate 
                 else dateadd(month,datediff(month,0,dateadd(day,1,monthEnd))+1,0)-1 end
    from cte
    where monthEnd<@EndDate
)
select * from cte

输出

startDate   endDate month   monthStart  monthEnd
2016-11-25  2017-02-20  Nov-16  2016-11-25  2016-11-30
2016-11-25  2017-02-20  Dec-16  2016-12-01  2016-12-31
2016-11-25  2017-02-20  Jan-17  2017-01-01  2017-01-31
2016-11-25  2017-02-20  Feb-17  2017-02-01  2017-02-20

希望这会对你有所帮助