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

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

    declare @StartDate datetime
    declare @EndDate datetime
    select @StartDate = '2011-01-01' ,  @EndDate = '2011-08-01'
    
    select @StartDate= @StartDate-(DATEPART(DD,@StartDate)-1)
    
    declare @temp  table
    (
    TheDate datetime
    )
    while (@StartDate<=@EndDate)
    begin
    insert into @temp
    values (@StartDate )
    select @StartDate=DATEADD(MM,1,@StartDate)
    end
    select * from @temp
    

    Works even if the @StartDate is not the first day of the month by going back to the initial day of the month of StartDate

提交回复
热议问题