Get All Dates of Given Month and Year in SQL Server

后端 未结 11 1523
梦如初夏
梦如初夏 2021-02-19 11:22

I want to get all dates by declaring month and year in SQL server.

Can anyone please share easy lines of SQL code to get it.

For example:



        
11条回答
  •  萌比男神i
    2021-02-19 11:50

    Another CTE based version

    DECLARE @Month INT = 2, @Year INT = 2019
    
    ;WITH MonthDays_CTE(DayNum)
    AS
    (
    SELECT DATEFROMPARTS(@Year, @Month, 1) AS DayNum
    UNION ALL
    SELECT DATEADD(DAY, 1, DayNum)
      FROM MonthDays_CTE
      WHERE DayNum < EOMONTH(DATEFROMPARTS(@Year, @Month, 1))
    )
    SELECT *
      FROM MonthDays_CTE
    

提交回复
热议问题