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

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

    DECLARE @tmpTable table (LastDates DATE);
    DECLARE @startDate DATE = '01/01/2012'; --1 Jan 2012
    DECLARE @endDate DATE = '05/31/2012';   --31 May 2012
    DECLARE @tmpEndDate DATE;
    
    SET @startDate = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@startDate)+1,1));
    SET @tmpEndDate = DATEADD(DAY, 1, @endDate);
    
    WHILE (@startDate <= @tmpEndDate)
    BEGIN   
        INSERT INTO @tmpTable (LastDates) values (DATEADD(DAY, -1, @startDate));
        SET @startDate = DATEADD(MONTH, 1, @startDate);
    END
    
    SELECT [LastDates] FROM @tmpTable;
    

    Output:

    Example: 1

    @startDate DATE = '01/01/2012'; --1 Jan 2012
    @endDate DATE = '05/31/2012';   --31 May 2012
    
    LastDates
    ----------
    2012-01-31
    2012-02-29
    2012-03-31
    2012-04-30
    2012-05-31
    

    Example: 2

    @startDate DATE = '11/01/2011'; --1 Nov 2011
    @endDate DATE = '03/13/2012';   --13 Mar 2012
    
    LastDates
    ----------
    2011-11-30
    2011-12-31
    2012-01-31
    2012-02-29
    

提交回复
热议问题