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

前端 未结 9 1799
深忆病人
深忆病人 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:21

    I've created a table variable, filled it with all days between @startDate and @endDate and searched for max date in the month.

    declare @tmpTable table (dates date)
    declare @startDate date = '08/08/2013'
    declare @endDate date = '11/11/2013'
    
    while @startDate <= @endDate
    begin
        insert into @tmpTable (dates) values (@startDate)
        set @startDate = DATEADD(DAY, 1, @startDate)
    end
    
    select max(dates) as [Last day] from @tmpTable as o
    group by datepart(YEAR, dates), datepart(MONTH, dates)
    

    Results:

    Last day
    2013-08-31
    2013-09-30
    2013-10-31
    2013-11-11
    

    To also get last day of November this can be used before loop:

    set @endDate = DATEADD(day, -1, DATEADD(month, DATEDIFF(month, 0, @endDate) + 1, 0))
    

提交回复
热议问题