Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

sql server - better way to generate months/year table

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?

DECLARE @FromDate DATETIME, @ToDate DATETIME
SET @FromDate = '2012-01-01 00:00:00.000'
SET @ToDate = '2012-31-12 23:59:59.000'

DECLARE @MonthsAndYears table (Month INT, Year int)

;WITH dates AS 
(
    SELECT @FromDate 'date'
        UNION ALL
    SELECT DATEADD(dd, 1, t.date) 
        FROM dates t
    WHERE DATEADD(dd, 1, t.date) <= @ToDate
)
INSERT INTO @MonthsAndYears
SELECT 
    DATEPART(MONTH, date),
    DATEPART(YEAR, date)
FROM dates 
GROUP BY 
DATEPART(MONTH, date),
DATEPART(YEAR, date)
option (maxrecursion 0)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...