Get All Dates of Given Month and Year in SQL Server

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

    CREATE FUNCTION fn_GetMonthlyDates
    (
      @ProcessDate smalldatetime
    )
    RETURNS @LOAN TABLE 
    (
     ProcessDate    smalldatetime
    )
    AS
    BEGIN
        DECLARE 
            @Today DATE= @ProcessDate,
            @StartOfMonth DATE ,
            @EndOfMonth DATE;
    
        DECLARE @DateList TABLE (DateLabel VARCHAR(10) );
        SET @EndOfMonth = EOMONTH(@Today);
        SET @StartOfMonth = DATEFROMPARTS(YEAR(@Today), MONTH(@Today), 1);
    
        WHILE @StartOfMonth <= @EndOfMonth
        BEGIN
           INSERT  INTO @DateList
           VALUES  (@StartOfMonth );
           SET @StartOfMonth = DATEADD(DAY, 1, @StartOfMonth);
        END;
    
        INSERT INTO @LOAN(ProcessDate)
        SELECT  DateLabel
        FROM    @DateList; 
    
    RETURN
    END
    

提交回复
热议问题