Thursday 7 June 2012

Quick way to populate Time Dimension




CREATE TABLE [dbo].[DimPeriod](
[PK_Date] [datetime] Primary key NOT NULL,
Day_Name varchar(150) not null,
[Year] datetime not null,
[Year_Name] varchar (50) not null,
[Quarter] datetime not null,
[Quarter_Name] [varchar](50) not null,
[Month] datetime not null,
[Month_Name] [varchar](50) not null,
[Day_Of_Year] [int] not null,
[Day_Of_Month] [int] not null
)
go




Declare @stdate datetime, @enddate datetime
select
 @stdate = '2006-01-01',
 @enddate = '2020-12-31'

set @stdate = DATEADD(dd, -1, @stdate)



Insert into DimPeriod
select dt,
DateName(WEEKDAY, dt) + ', ' + CONVERT(varchar(11), dt, 100),
--CONVERT(varchar(100), dt,
cast(yy as datetime),
'Year ' + cast(YEAR(dt) as CHAR(4)),
dateadd(q, DATEPART(Q, dt) - 1, yy),
'Quater ' + CAST(DATEPART(q, dt) as CHAR(1)),
cast(cast(YEAR(dt) as CHAR(4)) + '-' + cast(DATEPART(Month, dt) as CHAR(2)) + '-1' as datetime),
DATENAME(Month, dt) + ' ' + cast(YEAR(dt) as CHAR(4)),
DATEPART(DAYOFYEAR, dt), DAY(dt)

  from (
SELECT TOP (DATEDIFF(DD, @stdate, @enddate))
 cast(DatePart(YEAR, DATEADD(dd, row_number()  over(order by t1.number), '2005-12-31')) as CHAR(4))
+ '-01-01' yy,
 DATEADD(dd, row_number()  over(order by t1.number), '2005-12-31') as dt
FROM master..spt_values t1
    CROSS JOIN master..spt_values t2
)sq

No comments:

Post a Comment