Jeg foretrækker at bruge sæt, der allerede eksisterer, da det ofte er meget mere effektivt end dyre rekursive CTE'er. Hvis du har en taltabel, så brug den; hvis du allerede har et kalenderbord, endnu bedre; Ellers kan du bruge indbyggede objekter som 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 lidt baggrund, se:
- 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