Forum Posts

Visitors Online

Generating a Date Dimension the easy way

While there are different views on how to build different dimensions, there seems to be a common view of how, at least the basic information, of date dimensions looks. This can take a little time to build out. To help in building this dimension, I created a simple table valued function that takes in a start date and returns a date dimension table.

/*******************************************************************************************************
** Name: dbo.GenerateDateDimension
** Desc: Takes a start date and returns all dates up to the current day as a Date Dimension table.
** Auth: Cliff Buckley (SQLSlayer.com)
** Parameters: @StartDate - The starting date for the date dimension table.
** Dependancies: None
** Notes:
** Date: 10.07.2009
** Example: SELECT * FROM dbo.GenerateDateDimension('1/1/2009')
*******************************************************************************
** Change History
*******************************************************************************
** Date: Author: Description:
** -------- -------- ---------------------------------------
**
********************************************************************************************************/
CREATE FUNCTION dbo.GenerateDateDimension
(
@StartDate datetime
)
RETURNS @DimDate TABLE(DateId int,YearNumber smallint, QuarterNumber tinyint, MonthText varchar(20)
,MonthNumber tinyint,DayNumberOfMonth tinyint, DayOfWeekText varchar(20)
,DayNumberOfYear smallint,SQLDate datetime)
AS
BEGIN
DECLARE @EndDate datetime

SET @EndDate = CAST(CONVERT(varchar(8),getdate(),112) as datetime)

WHILE @StartDate <= @EndDate
BEGIN
INSERT INTO @DimDate(DateId,YearNumber,QuarterNumber,MonthText,MonthNumber,DayNumberOfMonth,DayOfWeekText,DayNumberOfYear,SQLDate)
SELECT CAST(CONVERT(varchar(8),@StartDate,112) AS INT) AS DateId
,DATENAME(year,@StartDate) AS YearNumber
,DATENAME(quarter,@StartDate) AS QuarterNumber
,DATENAME(month,@StartDate) AS MonthText
,MONTH(@StartDate) AS MonthNumber
,DATENAME(day,@StartDate) AS DayOfMonthNumber
,DATENAME(weekday,@StartDate) AS DayOfWeekText
,DATENAME(dayofyear,@StartDate) AS DayNumberOfYear
,@StartDate AS SQLDate
SET @StartDate = DATEADD(d, 1, @StartDate)
END

RETURN;
END
GO

Unfortunately, the formatting is lost, but you get the idea.

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Twitter
  • email
  • LinkedIn

Leave a Reply

 

 

 

Quicktags: