Five ways to generate a date record table

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.