Get All Dates of Given Month and Year in SQL Server

后端 未结 11 1553
梦如初夏
梦如初夏 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条回答
  •  既然无缘
    2021-02-19 11:47

    Little modification. Query given by @t-clausen.dk will give you correct result only if you ran it on first of the month. With little change this works awesome.

    DECLARE @date DATE = getdate()
    
    ;WITH N(N)AS 
    (SELECT 1 FROM(VALUES(1),(1),(1),(1),(1),(1))M(N)),
    tally(N)AS(SELECT ROW_NUMBER()OVER(ORDER BY N.N)FROM N,N a)
    
    
    SELECT top(day(EOMONTH(@date)))
     N day,
     DATEFROMPARTS(year(@date),month(@date), n) date
    FROM tally
    

    BTW nice trick t-clausen.dk. I couldn't think of more easy way

提交回复
热议问题