Tuesday, November 01, 2011

Creating a table with dates, weeks and days

Call me crazy but I prefer having all dates, days and weeks in one table to use in queries. This little loop gives me exactly that. It'll insert date, year, week, day-of-week, day-of-year, yyyy-ww and yymm, into the table ALM.

Mind the iso_week och isoww parts need SQL Server 2008 or greater.
SET DATEFIRST 1
GO

declare
@date as smalldatetime,
@Year as INTEGER,
@vv as INTEGER,
@d as INTEGER,
@daynumber as integer,
@MONTH AS CHAR(2),
@Count as integer,
@current as integer,
@AAAAVV AS CHAR(7),
@AAMM AS CHAR(4),
@startdate as smalldatetime

set @startdate='2012-01-01'
set @current=0
set @count = (select datepart(dayofyear,'2022-12-31'))

WHILE (@current < @count)
BEGIN
set @date=DATEADD(day, @current, @startdate)
set @daynumber = datepart(dy,@date)
set @Year = datepart(yyyy,@date)

set @vv = RIGHT('0' + CAST(datepart(isoww,@date) AS VARCHAR(2)),2)

if (DATEPART(ISO_WEEK, @date) > DATEPART(week, @date))
begin
SET @AAAAVV = cast(DATEPART(yyyy, dateadd(yyyy,-1, @date)) as varchar(4)) + '-' + RIGHT('0' + CAST(datepart(isoww, @date) AS VARCHAR(2)),2)
end

else
begin
SET @AAAAVV = CAST(@YEAR AS CHAR(4)) + '-' + RIGHT('0' + CAST(datepart(isoww, @date) AS VARCHAR(2)),2)
end

set @d = datepart(dw,@date)
SET @MONTH = RIGHT('0' + CAST(DATEPART(MM, @DATE) AS VARCHAR(2)),2)

SET @AAMM = RIGHT(@YEAR, 2) + CAST(@MONTH AS CHAR(2))

insert into ALM(DATUM, AAAA, VV, D, DAGNR, AAAAVV, AAMM)
values(@DATE, @YEAR, @VV, @D, @daynumber, @AAAAVV, @AAMM)

set @current=@current+1
END
GO