Get All Dates of Given Month and Year in SQL Server

后端 未结 11 1504
梦如初夏
梦如初夏 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:53

    You can't get all days just by declaring the month, you need to add the year as well because of leap years:

    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,
      dateadd(d,N-1, @date) date
    FROM tally
    

    Another different solution(by t@clausen):

    DECLARE @month AS INT = 5
    DECLARE @Year AS INT = 2016
    
    ;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 N day,datefromparts(@year,@month,N) date FROM tally
    WHERE N <= day(EOMONTH(datefromparts(@year,@month,1)))
    

提交回复
热议问题