tsql: How to retrieve the last date of each month between given date range

前端 未结 9 1788
深忆病人
深忆病人 2020-12-06 22:00

I have two date for example 08/08/2013 and 11/11/2013 and I need last date of each month starting from August to November in a table so that i can iterate over the table to

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-06 22:17

    You can use CTE for getting all last days of the month within the defined range

    Declare @Start datetime
    Declare @End datetime
    
    Select @Start = '20130808'
    Select @End = '20131111'
    ;With CTE as
    (
    Select @Start  as Date,Case When DatePart(mm,@Start)<>DatePart(mm,@Start+1) then 1 else 0 end as [Last]
    UNION ALL
    Select Date+1,Case When DatePart(mm,Date+1)<>DatePart(mm,Date+2) then 1 else 0 end from CTE
    Where Date<@End
    )
    
    Select * from CTE
    where [Last]=1   OPTION ( MAXRECURSION 0 )
    

提交回复
热议问题