我开始再次使用更多的tsql。有没有比下面的更好的方法来生成一个包含开始和结束日期的月份和年份整数的表?
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)
答案 0 :(得分:10)
我更喜欢使用已经存在的集合,因为这通常比昂贵的递归CTE更有效。如果您有数字表,请使用它;如果你已经有一个日历表,那就更好了;否则,您可以使用内置对象,如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;
有些背景,请参阅: