better way to generate months/year table

前端 未结 1 1364
迷失自我
迷失自我 2020-12-12 03:18

I am starting to use more tsql again. Is there a better way then the one below to generate a table containing the month and year integers given a start and end date?

相关标签:
1条回答
  • 2020-12-12 03:50

    I prefer to use sets that already exist, since that is often much more efficient than expensive recursive CTEs. If you have a numbers table, use it; if you have a calendar table already, even better; otherwise, you can use built in objects like master.dbo.spt_values:

    DECLARE @FromDate DATETIME, @ToDate DATETIME;
    SET @FromDate = '2012-01-01';
    SET @ToDate = '2012-12-31';
    
    -- all days in that period
    SELECT TOP (DATEDIFF(DAY, @FromDate, @ToDate)+1) 
      TheDate = DATEADD(DAY, number, @FromDate)
      FROM [master].dbo.spt_values 
      WHERE [type] = N'P' ORDER BY number;
    
    -- just the months in that period
    SELECT TOP (DATEDIFF(MONTH, @FromDate, @ToDate)+1) 
      TheDate  = DATEADD(MONTH, number, @FromDate),
      TheMonth = MONTH(DATEADD(MONTH, number, @FromDate)),
      TheYear  = YEAR(DATEADD(MONTH, number, @FromDate))
      FROM [master].dbo.spt_values 
      WHERE [type] = N'P' ORDER BY number;
    

    For some background, see:

    • http://www.sqlperformance.com/2013/01/t-sql-queries/generate-a-set-1
    • http://www.sqlperformance.com/2013/01/t-sql-queries/generate-a-set-2
    • http://www.sqlperformance.com/2013/01/t-sql-queries/generate-a-set-3
    0 讨论(0)
提交回复
热议问题