t-sql select get all Months within a range of years

前端 未结 8 574
悲哀的现实
悲哀的现实 2020-12-18 05:06

I need a select to return Month and year Within a specified date range where I would input the start year and month and the select would return month and year from the date

8条回答
  •  -上瘾入骨i
    2020-12-18 05:48

    Gosh folks... using a "counting recursive CTE" or "rCTE" is as bad or worse than using a loop. Please see the following article for why I say that.

    http://www.sqlservercentral.com/articles/T-SQL/74118/

    Here's one way to do it without any RBAR including the "hidden RBAR" of a counting rCTE.

    --===== Declare and preset some obviously named variables
    DECLARE @StartDate DATETIME,
            @EndDate   DATETIME
    ;
     SELECT @StartDate = '2010-01-14', --We'll get the month for both of these 
            @EndDate   = '2020-12-05'  --dates and everything in between
    ;
    WITH
    cteDates AS
    (--==== Creates a "Tally Table" structure for months to add to start date
         -- calulated by the difference in months between the start and end date.
         -- Then adds those numbers to the start of the month of the start date.
     SELECT TOP (DATEDIFF(mm,@StartDate,@EndDate) + 1)
            MonthDate = DATEADD(mm,DATEDIFF(mm,0,@StartDate) 
                      + (ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) -1),0)
       FROM sys.all_columns ac1
      CROSS JOIN sys.all_columns ac2
    )
    --===== Slice each "whole month" date into the desired display values.
     SELECT [Year]  = YEAR(MonthDate),
            [Month] = MONTH(MonthDate) 
       FROM cteDates
    ;
    

提交回复
热议问题