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

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

    This works even if the @StartDate is not the first of the month. I'm assuming that if it's not the start of the month, you want to begin with the first of the next month. Otherwise remove the +1.:

    ;WITH cte AS (
    SELECT CASE WHEN DATEPART(Day,@StartDate) = 1 THEN @StartDate 
                ELSE DATEADD(Month,DATEDIFF(Month,0,@StartDate)+1,0) END AS myDate
    UNION ALL
    SELECT DATEADD(Month,1,myDate)
    FROM cte
    WHERE DATEADD(Month,1,myDate) <=  @EndDate
    )
    SELECT myDate
    FROM cte
    OPTION (MAXRECURSION 0)
    

提交回复
热议问题