首页 > 数据库技术 > 详细

Sqlserver存储过程生成日期维度

时间:2015-12-18 18:28:24      阅读:562      评论:0      收藏:0      [点我收藏+]

话不多说,之前已经有一篇日志是利用oracle的存储过程生成日期维度表,接下来我们就用sqlserver来实现这个操作,如下面的步骤所示

1:创建日期维度表(Dim_time)

 

CREATE TABLE [dbo].[Dim_time](
    [the_date] [nvarchar](50) NOT NULL,
    [date_name] [nvarchar](15) NULL,
    [the_year] [int] NULL,
    [year_name] [nvarchar](10) NULL,
    [the_quarter] [nvarchar](10) NULL,
    [quarter_name] [nvarchar](10) NULL,
    [the_month] [int] NULL,
    [month_name] [nvarchar](10) NULL,
    [the_week] [int] NULL,
    [week_name] [nvarchar](10) NULL,
    [week_day] [nvarchar](10) NULL
)

2:创建生成日期维表数据的存储过程

alter PROCEDURE SP_CREATE_TIME_DIMENSION
@begin_date  nvarchar(50)=2015-12-01 ,
@end_date    nvarchar(50)=2015-12-31
as
/*
  SP_CREATE_TIME_DIMENSION: 生成时间维数据
  begin_date: 起始时间
  end_date:结束时间
*/
declare 
@dDate date=convert(date,@begin_date),
@v_the_date varchar(10),
@v_the_year varchar(4),
@v_the_quarter varchar(2),
@v_the_month varchar(10),
@v_the_month2 varchar(2),
@v_the_week varchar(2),
@v_the_day varchar(10),
@v_the_day2 varchar(2),
@v_week_day nvarchar(10),
@adddays int=1;
WHILE (@dDate<=convert(date,@end_date))
begin
set @v_the_date=convert(char(10),@dDate,120);--key值
set @v_the_year=DATEPART("YYYY",@dDate);--set @v_the_quarter=DATEPART("QQ",@dDate);--季度"
set @v_the_month=DATEPART("MM",@dDate);--月份(字符型)
--set @v_the_month2=to_number(to_char(dDate, mm));--月份(数字型)
set @v_the_day=DATEPART("dd",@dDate);--日(字符型)
--set @v_the_day2=to_char(dDate, dd);
set @v_the_week=DATEPART("WW",@dDate);--年的第几周
set @v_week_day=DATEPART("DW",@dDate); --星期几
insert into Dim_time(the_date,date_name,the_year,year_name,the_quarter,quarter_name,the_month,month_name,the_week,week_name,week_day)
values(
@v_the_date,convert(nvarchar(10),@v_the_year)++convert(nvarchar(10),@v_the_month)++convert(nvarchar(10),@v_the_day)+,
@v_the_year,convert(nvarchar(10),@v_the_year)+,
convert(nvarchar(10),@v_the_year)+Q+convert(nvarchar(10),@v_the_quarter),
convert(nvarchar(10),@v_the_year)++convert(nvarchar(10),@v_the_quarter)+季度,
convert(int,(convert(nvarchar(10),@v_the_year)+convert(nvarchar(10),@v_the_month))),
convert(nvarchar(10),@v_the_year)++convert(nvarchar(10),@v_the_month)+,
@v_the_week
,+convert(nvarchar(10),@v_the_week)+,
@v_week_day
);
set @dDate=dateadd(day,@adddays,@dDate);
continue
if @dDate=dateadd(day,-1,convert(date,@end_date))
break
end
go

3:执行存储过程

USE [DW]
GO

DECLARE    @return_value int

EXEC    @return_value = [dbo].[SP_CREATE_TIME_DIMENSION]

SELECT    Return Value = @return_value

GO

4:开始时间和结束时间默认值是2015年12月份,所以下面就生成了12月份的日期维度自定义表

技术分享

5:注意和扩展

    a:可以根据思路运用到各种数据库当中,例如本文就是根据oracle的procedure改造过来的

    b:注意上表中的最后一个字段week_day星期几的字段,星期一 至 星期天依次为 2,3,4,5,6,7,1

Sqlserver存储过程生成日期维度

原文:http://www.cnblogs.com/wxjnew/p/5057713.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!