Easiest way to populate a temp table with dates between and including 2 date parameters

前端 未结 8 1682
旧时难觅i
旧时难觅i 2020-11-27 06:34

What is the easiest way to populate a temp table with dates including and between 2 date parameters. I only need the 1st day of the month dates.

So for example if @S

8条回答
  •  没有蜡笔的小新
    2020-11-27 06:50

    Solution:

    DECLARE  @StartDate DATETIME
            ,@EndDate DATETIME;
    
    SELECT   @StartDate = '20110105'
            ,@EndDate = '20110815';
    
    SELECT  DATEADD(MONTH, DATEDIFF(MONTH, 0, DATEADD(MONTH, v.number, @StartDate)), 0) AS FirstDay
    --or Andriy M suggestion:
    --SELECT    DATEADD(MONTH, DATEDIFF(MONTH, 0, @StartDate) + v.number, 0) AS FirstDay
    INTO    #Results
    FROM    master.dbo.spt_values v
    WHERE   v.type = 'P'        
    AND     DATEDIFF(MONTH, @StartDate, @EndDate) >= v.number;
    
    SELECT  *
    FROM    #Results;
    
    DROP TABLE #Results;
    

    Results:

    FirstDay
    -----------------------
    2011-01-01 00:00:00.000
    2011-02-01 00:00:00.000
    2011-03-01 00:00:00.000
    2011-04-01 00:00:00.000
    2011-05-01 00:00:00.000
    2011-06-01 00:00:00.000
    2011-07-01 00:00:00.000
    2011-08-01 00:00:00.000
    

提交回复
热议问题