Original article: http://sqlblogcasts.com/blogs/tomaztsql/archive/2011/07/04/datetime-tally-table.aspx
Five ways to generate a date record table (although there are five ways to write a text like Kong Yiji, it is helpful to learn t-SQL ):
-- Method 1.
; Create Table TC .. dt
(ID int identity (1, 1)
, DT datetime)
Insert into DT (DT)
Select
A. dt + B. Number as dt
From
(Select cast ('2014/1/31' as datetime) as dt
) As
Cross join Master .. spt_values as B
Where
Type = 'p' and number between 1 and 365
This method is very efficient, but requires the access permission of the master database.
-- Method 2.
; Create Table TC .. dt
(ID int identity (1, 1)
, DT datetime)
; With tab
(
Select cast ('1970-1-1 'As datetime) as DT, 1 as Rn
Union all
Select dateadd (day, 1, DT) as DT, rn + 1 as Rn
From Tab
Where rn< 365
)
Insert into DT (DT)
Select dt
From Tab
Option (maxrecursion 365)
-- Method 3.
; Create Table TC .. dt
(ID int identity (1, 1)
, DT datetime)
Insert into DT (DT)
; Select
Cast ('2014/1/31' as datetime) + number as dt
From master .. spt_values as B
Where
Type = 'p' and number between 1 and 365
-- Annotation: Same method 1
-- Method 4.
; Create Table TC .. dt
(ID int identity (1, 1)
, DT datetime)
Insert into DT (DT)
Select
Dateadd (day, isnull (select scope_identity (), 2), '2014/1/31 ')
Go 1, 365
This method is very inefficient and is not recommended. It can be used for testing only.
-- Method 5.
; Create Table TC .. dt
(ID int identity (1, 1)
, DT datetime)
While isnull (@ identity, 1) <= 365
Begin
Insert into DT (DT)
Select
Dateadd (day, isnull (@ identity, 1), '2017/31') as dt
End