码迷,mamicode.com
首页 > 其他好文 > 详细

日期维度表代码

时间:2015-02-12 15:44:08      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:

-- We should create a date dimension table in the database
CREATE TABLE dbo.DimDates (
  [DateKey] int NOT NULL PRIMARY KEY IDENTITY
, [Date] datetime NOT NULL
, [DateName] nVarchar(50)
, [Month] int NOT NULL
, [MonthName] nVarchar(50) NOT NULL
, [Quarter] int NOT NULL
, [QuarterName] nVarchar(50) NOT NULL
, [Year] int NOT NULL
, [YearName] nVarchar(50) NOT NULL
)

-- Since the date table has no associated source table we can fill the data
-- using a SQL script or wait until the ETL process. Either way, here is the 
-- code to use.

-- Create variables to hold the start and end date
DECLARE @StartDate datetime = 01/01/1990
DECLARE @EndDate datetime = 01/01/1995 

-- Use a while loop to add dates to the table
DECLARE @DateInProcess datetime
SET @DateInProcess = @StartDate

WHILE @DateInProcess <= @EndDate
 BEGIN
 -- Add a row into the date dimension table for this date
 INSERT INTO DimDates 
 ( [Date], [DateName], [Month], [MonthName], [Quarter], [QuarterName], [Year], [YearName] )
 VALUES ( 
  @DateInProcess -- [Date]
  , DateName( weekday, @DateInProcess )  -- [DateName]  
  , Month( @DateInProcess ) -- [Month]   
  , DateName( month, @DateInProcess ) -- [MonthName]
  , DateName( quarter, @DateInProcess ) -- [Quarter]
  , Q + DateName( quarter, @DateInProcess ) +  -  + Cast( Year(@DateInProcess) as nVarchar(50) ) -- [QuarterName] 
  , Year( @DateInProcess )
  , Cast( Year(@DateInProcess ) as nVarchar(50) ) -- [Year] 
  )  
 -- Add a day and loop again
 SET @DateInProcess = DateAdd(d, 1, @DateInProcess)
 END

-- Check the table SELECT Top 10 * FROM DimDates

/****** Create the Fact Tables ******/

CREATE TABLE [dbo].[FactTitlesAuthors](
    [TitleKey] [int] NOT NULL,
    [AuthorKey] [int] NOT NULL,
    [AuthorOrder] [int] NOT NULL,
 CONSTRAINT [PK_FactTitlesAuthors] PRIMARY KEY CLUSTERED 
    ( [TitleKey] ASC, [AuthorKey] ASC )
)
GO

 

-- Adding additional lookup values to the DimDates table 

Set Identity_Insert [DimDates] On -- 把IDENTITY自增ID关掉
INSERT INTO [DWPubsSales].[dbo].[DimDates] ( 
   [DateKey] -- This is normally added automatically
 , [Date]
 , [DateName]
 , [Month]
 , [MonthName]
 , [Quarter]
 , [QuarterName]
 , [Year]
 , [YearName]
 )
VALUES
 ( -1 -- This will be the Primary key for the first lookup value 
 , 01/01/1900
 , Unknown Day
 , -1
 , Unknown Month
 , -1
 , Unknown Quarter
 , -1 
 , Unknown Year 
 )
,  -- add a second row
( -2 -- This will be the Primary key for the second lookup value
 , 02/01/1900
 , Corrupt Day
 , -2
 , Corrupt Month
 , -2
 , Corrupt Quarter
 , -2 
 , Corrupt Year 
 )
Set Identity_Insert [DimDates] Off  

 

日期维度表代码

标签:

原文地址:http://www.cnblogs.com/haseo/p/4287834.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!