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

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

    You can use a recursive CTE to do this, note the MAXRECURSION OPTION prevents an infinite loop:

    DECLARE @StartDate DATE = '2013-08-08'
    DECLARE @EndDate DATE = '2013-11-11'
    
    ;WITH dateCTE
    AS
    (
        SELECT CAST(DATEADD(M, 1,DATEADD(d, DAY(@StartDate) * -1, @StartDate)) AS DATE) EndOFMonth
        UNION ALL 
        SELECT CAST(DATEADD(M, 2,DATEADD(d, DAY(EndOFMonth) * -1, EndOFMonth)) AS DATE) 
        FROM dateCTE
        WHERE EndOFMonth < DATEADD(d, DAY(@EndDate) * -1, @EndDate)
    
    )
    SELECT *
    FROM dateCTE
    OPTION (MAXRECURSION 30);
    

    This returns

    EndOFMonth
    ----------
    2013-08-31
    2013-09-30
    2013-10-31
    

提交回复
热议问题