在數據倉庫的創建過程中,往往需要創建日期維度來為以后的數據分析來服務。
方面從多個日期角度:
如:年-月-日,年-季度-月-日,年-周-日
創建表的腳本如下(存儲過程的創建過程中有一步操作是向time_dimension表中插入數據,所以首先需要創建好此表)

create table TIME_DIMENSION ( the_date NUMBER not null, date_name NVARCHAR2(15), the_year NUMBER, year_name NVARCHAR2(10), the_quarter VARCHAR2(10), quarter_name NVARCHAR2(10), the_month NUMBER, month_name NVARCHAR2(10), the_week NUMBER, week_name NVARCHAR2(10), week_day NVARCHAR2(10) ) tablespace TBS_COGNOS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64 next 1 minextents 1 maxextents unlimited );
存儲過程腳本如下

CREATE OR REPLACE PROCEDURE SP_CREATE_TIME_DIMENSION(begin_date in varchar2, end_date in varchar2) is /*SP_CREATE_TIME_DIMENSION: 生成時間維數據 begin_date: 起始時間 end_date:結束時間 */ dDate date; v_the_date number; v_the_year varchar2(4); v_the_quarter varchar2(2); v_the_month varchar2(10); v_the_month2 varchar2(2); v_the_week varchar2(2); v_the_day varchar2(10); v_the_day2 varchar2(2); v_week_day nvarchar2(10); adddays int; BEGIN adddays := 1 ; dDate := to_date(begin_date,'yyyymmdd'); WHILE (dDate <= to_date(end_date,'yyyymmdd')) loop v_the_date := to_number(to_char(dDate,'yyyymmdd'));--key值 v_the_year:= to_char(dDate, 'yyyy');--年 v_the_quarter := to_char(dDate, 'q');--季度 v_the_month:=to_char(dDate, 'mm');--月份(字符型) v_the_month2:=to_number(to_char(dDate, 'mm'));--月份(數字型) v_the_day:=to_char(dDate, 'dd');--日(字符型) v_the_day2:=to_char(dDate, 'dd'); v_the_week:= to_char(dDate,'fmww');--年的第幾周 v_week_day := to_char(dDate, 'day'); --星期幾 insert into time_dimension(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,v_the_year||'年'||v_the_month2||'月'||v_the_day2||'日',v_the_year,v_the_year||'年', v_the_year||'Q'||v_the_quarter,v_the_year||'年'||v_the_quarter||'季度',to_number(v_the_year||v_the_month), v_the_year||'年'||v_the_month2||'月',v_the_week,'第'||v_the_week||'周', v_week_day); dDate := dDate + adddays; END loop; end SP_CREATE_TIME_DIMENSION;
OK,存儲過程創建完畢,下面我們需要傳參並且只需存儲過程,問題來了,如何通過PLSQL執行存儲過程?之前都是在PLSQL中創建 SQL 窗口來執行procedure
結果報錯,其實應該創建 命令窗口 來執行procedure
如下圖:
命令窗口的執行腳本如下:
SQL> exec SP_CREATE_TIME_DIMENSION(20140101,20140630); PL/SQL procedure successfully completed SQL> commit; Commit complete SQL> select * from time_dimension;
OK,截止目前,日期維度已經生成。