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

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

提交回复
热议问题