Get All Dates of Given Month and Year in SQL Server

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

    Here is a query:

    DECLARE @ReportDate VARCHAR(20)='2019-02-10'
    
    DECLARE @LastDay INT =DAY(EOMONTH(@ReportDate))
    
    DECLARE @DayStart INT=01
    
    CREATE TABLE #TEMPMonth ([MDay] VARCHAR(20))
    
    WHILE @LastDay>=@DayStart
    
    BEGIN
        
    INSERT INTO #TEMPMonth 
        
    SELECT CAST(CAST(YEAR(@ReportDate)AS VARCHAR)+'-'+CAST(MONTH(@ReportDate)AS VARCHAR)+'-'+CAST(@DayStart AS VARCHAR) AS DATE)
        SET @DayStart+=1
    
    END
    
    SELECT * FROM #TEMPMonth
    
    DROP TABLE #TEMPMonth
    

提交回复
热议问题