勤奋的码农
欢迎光临我的淘宝店:小丑情趣内衣店

ALTER PROCEDURE [dbo].[Create_time_by_day_dimension] 

    -- Add the parameters for the stored procedure here

AS

BEGIN

    -- SET NOCOUNT ON added to prevent extra result sets from

    -- interfering with SELECT statements.

SET NOCOUNT ON;

begin try

drop table [time_by_day_dimension]

end try

begin catch

end catch 

CREATE TABLE [dbo].[time_by_day_dimension] ( 

  [time_id] [int] IDENTITY (1, 1) NOT NULL , 

  [the_date] [datetime] NULL , 

  [the_day] [nvarchar] (15) NULL , 

  [the_month] [nvarchar] (15) NULL , 

  [the_year] [smallint] NULL , 

  [day_of_month] [smallint] NULL , 

  [week_of_year] [smallint] NULL , 

  [month_of_year] [smallint] NULL , 

  [quarter] [nvarchar] (2) NULL , 

  [fiscal_period] [nvarchar] (20) NULL 

) ON [PRIMARY] 

DECLARE @WeekString varchar(12), 

@dDate SMALLDATETIME, 

@sMonth varchar(20), 

@iYear smallint, 

@iDayOfMonth smallint, 

@iWeekOfYear smallint, 

@iMonthOfYear smallint, 

@sQuarter varchar(2), 

@sSQL varchar(100), 

@adddays int 

  

SELECT @adddays = 1 --日期增量(可以自由设定)

SELECT @dDate = '01/01/2006' --开始日期

  

WHILE @dDate < '12/31/2010' --结束日期

BEGIN

  

  SELECT @WeekString = DATENAME (dw, @dDate) 

  SELECT @sMonth=DATENAME(mm,@dDate) 

  SELECT @iYear= DATENAME (yy, @dDate) 

  SELECT @iDayOfMonth=DATENAME (dd, @dDate) 

  SELECT @iWeekOfYear= DATENAME (week, @dDate) 

  SELECT @iMonthOfYear=DATEPART(month, @dDate) 

  SELECT @sQuarter = 'Q' + CAST(DATENAME (quarter, @dDate)as varchar(1)) 

  INSERT INTO time_by_day_dimension(the_date, the_day, the_month, the_year, 

  day_of_month, 

  week_of_year, month_of_year, quarter) VALUES 

  (@dDate, @WeekString, @sMonth, @iYear, @iDayOfMonth, @iWeekOfYear, 

  @iMonthOfYear, @sQuarter) 

  SELECT @dDate = @dDate + @adddays 

END

END

如果时间维度的粒度精确到天的话,建议time_id不用自增列,使用
cast(the_day as int)来填充该列,可以避免事实表和维度表进行关联。当然使用自增列也可以避免关联,不过要做一些处理

按照kimball的设计理念,timekey最好是有意义的数值,如:1995-01-01 00:00:00转化成数值型可以是:19950101。
故按照bluexanadu的脚本,timekey可以这样写:
select cast((
left(convert(nvarchar,thedate,23),4)+
substring(convert(nvarchar,thedate,23),6,2)+
substring(convert(nvarchar,thedate,23),9,2))
as int) from dim_date
其实你完全可以把1995-01-01 00:00:00转化成转化成整型,整型只有4个字节,存储空间小,而且处理起来方便。

declare @d datetime
set @d='1995-01-01 00:00:00'
select cast(@d as int)

结果是:
34698

你可以把这个结果转化成日期:

select cast(34698 as datetime)

结果是:
1995-01-01 00:00:00.000
posted on 2013-11-14 22:03  勤奋的码农  阅读(562)  评论(0编辑  收藏  举报

友荐云推荐