Get All Dates of Given Month and Year in SQL Server

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

    You can get all the dates of a month using the following query.

    declare @month int, @year int
    set @month = 2
    set @year = 2008
    
    SELECT
    CAST(CAST(@year AS VARCHAR) + '-' + CAST(@Month AS VARCHAR) + '-01' AS DATETIME) + Number
    FROM master..spt_values
    WHERE type = 'P'
    AND
    (CAST(CAST(@year AS VARCHAR) + '-' + CAST(@Month AS VARCHAR) + '-01' AS DATETIME) + Number )
    <
    DATEADD(mm,1,CAST(CAST(@year AS VARCHAR) + '-' + CAST(@Month AS VARCHAR) + '-01' AS DATETIME) )
    

    Hope this will help you.

提交回复
热议问题