Create Date Table
-
Posted on June 17, 2009 by Derek Dieter
-
0
A great thing to have in any database is a table that stores dates. It can save tons of space to have disparate tables reference one date table that can store meta data regarding each date. About 5000 rows can hold ten years worth of dates.
Fill in the start and end dates and this script will create a date table:
[cc lang=”sql”]
create table dates(
id int not null,
[date] as (yyyy+mm+dd),
yyyy char(4) not null,
mm char(2) not null,
dd char(2) not null,
[year] int not null check(year between 1582 and 4000), — Gregorian calender from 1582 (in most countries)
[month] tinyint not null check(month between 1 and 12),
[day] tinyint check(day between 1 and 31),
day_of_week tinyint,
day_name char(18),
month_name char(18),
constraint pk_dates_id primary key clustered(id),
constraint uc_unique_date unique([date]),
constraint chk_valid_date check(isdate((yyyy+mm+dd)) = 1) )
go
— Declare variables
declare @startdate datetime, @enddate datetime, @id int, @year int, @month int, @day int
— Initialize variables
set @startdate = ‘19980101’
set @enddate = ‘20121231’
select @id = 1,@year = year(@startdate),@month = month(@startdate),@day = day(@startdate)
— Populate dates table
while 1 = 1
begin
— insert the date table
insert dates(id,yyyy,mm,dd,[year],[month],[day])
values( @id,
substring(‘0000′,1,4-len(@year))+ltrim(@year),
substring(’00’,1,2-len(@month))+ltrim(@month),
substring(’00’,1,2-len(@day))+ltrim(@day),
@year,
@month,
@day )
— check for end condition and return
if (select [date] from dates where id = @id) = @enddate return
— recompute the variables
if @day < 28 set @day = @day + 1
else if @month in(1,3,5,7,8,10) and @day = 31 select @day = 1, @month = @month + 1
else if @month = 12 and @day = 31
begin
select @day = 1, @month = 1, @year = @year + 1
print @year
end
else if @month in(4,6,9,11) and @day = 30
select @day = 1, @month = @month + 1
— A leap year is any year divisible by four except years both divisible by 100 and not divisible by 400
else if @month = 2 and @day = 28 and not (@year%4 = 0 and not( @year%4 = 0 and @year%100 = 0 and @year%400 != 0 ))
select @day = 1, @month = @month + 1
–else
else if @month = 2 and @day = 29 and (@year%4 = 0 and not( @year%4 = 0 and @year%100 = 0 and @year%400 != 0 ))
select @day = 1, @month = @month + 1
else set @day = @day + 1
set @id = @id + 1
end
go
— Update the fields with name of month and weekday
update dates set
month_name = datename(mm,convert(datetime,date)),
day_of_week = weekdays.wd,
day_name = weekdays.dayname
from
( select id%7 as mod,datepart(dw,convert(datetime,date)) as wd,datename(dw,convert(datetime,date)) as dayname
from dates where date between ‘20040105’ and ‘20040111’ ) as weekdays
where
weekdays.mod = dates.id%7
go
select * from dates
[/cc]
- Comments (RSS)
- Trackback
- Permalink
Hi Derek,
the script does not work in sql 2008 r2.
if @day < 28 set @day = @day + 1
please advise