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

前端 未结 8 1624
旧时难觅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 07:01

    Correction for null dates:

    IF OBJECT_ID('tempdb..#dim') IS NOT NULL 
    
        DROP TABLE #dim
    
    CREATE  TABLE #dim ([date] DATE)
    
    if not @Begin_Date is null and not @End_Date is null
    
    begin
        INSERT #dim([date])
        SELECT d
        FROM(
    
          SELECT
              d = DATEADD(DAY, rn - 1, @Begin_Date)
          FROM 
          (
              SELECT TOP (DATEDIFF(DAY, @Begin_Date, @End_Date)) 
                  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;
    end
    
    0 讨论(0)
  • 2020-11-27 07:02

    this is tested in SQL 2008 R2

    Declare @StartDate datetime = '2015-03-01'
    Declare @EndDate datetime = '2015-03-31'
    declare @temp Table
    (
    DayDate datetime
    );
    
    WHILE @StartDate <= @EndDate
    begin
     INSERT INTO @temp (DayDate) VALUES (@StartDate);
     SET @StartDate = Dateadd(Day,1, @StartDate);
    end ;
    
    select * from @temp
    

    Result:

    DayDate
    -----------------------
    2015-03-01 00:00:00.000
    2015-03-02 00:00:00.000
    2015-03-03 00:00:00.000
    2015-03-04 00:00:00.000
    ...
    
    0 讨论(0)
提交回复
热议问题