Excel

Wednesday, December 14, 2011

Creating Time Dimension table & Data population

Script to create a simple Time Dimension Table using SQL script and populate data :

IF EXISTS (SELECT name FROM sysobjects WHERE name = 'TimeDimension' AND type = 'U')
DROP TABLE TimeDimension
GO
CREATE TABLE TimeDimension
(
[DateID] numeric(8,0) PRIMARY KEY CLUSTERED,
[Date] SMALLDATETIME, [Day] VARCHAR(10),
week varchar(10), [Month] VARCHAR(10),
[Quarter] varchar(10),
[Year] SMALLINT,
DayOfMonth SMALLINT,
DayOfYear smallint,
WeekOfYear SMALLINT,
MonthOfYear SMALLINT,
QuarterOfYear smallint,
[FinYear] nvarchar(10),
[FinMonthOfYear] smallint,
[FinWeekOfYear] smallint,
[FinWeek] varchar(10),
[FinQuarterOfYear] Smallint
)
GO DECLARE @CurrDate SMALLDATETIME

SET @CurrDate = '01/01/2008'
WHILE @CurrDate < getdate()+360
BEGIN
INSERT TimeDimension
([DateID],[Date], [Day], [Month], [Year], DayOfMonth, WeekOfYear, MonthOfYear, [Quarter],

DayOfYear,week,Quarterofyear)
VALUES
(
CONVERT(Varchar(10),@CurrDate,112), --Date-As-ID @CurrDate,-- theDate
DATENAME(dw, @CurrDate), -- theDay
DATENAME(month, @CurrDate), -- theMonth
YEAR(@CurrDate), -- theYear
DAY(@CurrDate), -- DayOfMonth
DATENAME(wk, @CurrDate), -- WeekOfYear
MONTH(@CurrDate), -- MonthOfYear
'Quarter' + DATENAME(quarter,@CurrDate), -- Quarter
datename(dy,@CurrDate), --Day of Year
'Week ' + Datename(wk,@CurrDate), --Week
DATENAME(quarter,@CurrDate)) --Quarterof year
SET @CurrDate = DATEADD(day, 1, @CurrDate)
END

The above script will create a TimeDimension table and it will populate dimensional data from 01/01/2008 upto 360 days from run date.

1 comment: