Saya lebih suka menggunakan set yang sudah ada, karena itu seringkali jauh lebih efisien daripada CTE rekursif yang mahal. Jika Anda memiliki tabel angka, gunakan itu; jika Anda sudah memiliki tabel kalender, lebih baik lagi; jika tidak, Anda dapat menggunakan objek bawaan seperti 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;
Untuk beberapa latar belakang, lihat:
- 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