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

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

    Although the question is about the last day which @bummi has already answered.

    But here is the solution for the first date which might be helpful for someone.

    Get the first dates of all the months in-between the @FromDate and @ToDate.

    DECLARE @FromDate DATETIME = '2019-08-13'
    DECLARE @ToDate DATETIME = '2019-11-25'
    
    ;WITH CTE
    AS 
    (
        SELECT DATEADD(DAY, -(DAY(@FromDate) - 1), @FromDate) AS FirstDateOfMonth
    
        UNION ALL
    
        SELECT DATEADD(MONTH, 1, FirstDateOfMonth)
        FROM CTE
        WHERE FirstDateOfMonth < DATEADD(DAY, -(DAY(@ToDate) - 1), @ToDate)
    )
    SELECT * FROM CTE
    

    Here is the result

    --Result
    2019-08-01 00:00:00.000
    2019-09-01 00:00:00.000
    2019-10-01 00:00:00.000
    2019-11-01 00:00:00.000
    

提交回复
热议问题