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

前端 未结 8 1699
旧时难觅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:36

    Interestingly, it is faster to create from enumerated data as per this article.

    DECLARE @StartDate DATE = '10001201';
    DECLARE @EndDate DATE   = '20000101';
    
    DECLARE @dim TABLE ([date] DATE)
    
    INSERT @dim([date])
    SELECT d
    FROM
    (
      SELECT
          d = DATEADD(DAY, rn - 1, @StartDate)
      FROM 
      (
          SELECT TOP (DATEDIFF(DAY, @StartDate, @EndDate)) 
              rn = ROW_NUMBER() OVER (ORDER BY s1.[object_id])
          FROM
              sys.all_objects AS s1
          CROSS JOIN
              sys.all_objects AS s2
          ORDER BY
              s1.[object_id]
      ) AS x
    ) AS y;
    

    On my machine, it's around 60% faster with large date ranges. The recursion method can populate 2000 years worth of data in around 3 seconds though, and looks a lot nicer, so I don't really recommend this method just for incrementing days.

提交回复
热议问题