Oracle数据库之oracle 用sql生成日历的方法
小标 2018-11-19 来源 : 阅读 1331 评论 0

摘要:本文主要向大家介绍了Oracle数据库之oracle 用sql生成日历的方法,通过具体的内容向大家展现,希望对大家学习Oracle数据库有所帮助。

本文主要向大家介绍了Oracle数据库之oracle 用sql生成日历的方法,通过具体的内容向大家展现,希望对大家学习Oracle数据库有所帮助。


BI分析中,经常需要将事实表与时间维度表关联起来,按年/月/日来逐层展示,常用的做法是创建一张日历表,结构类似如下:


create table T_BAS_CALENDAR
(
  d_year  NUMBER(4) not null,
  d_month NUMBER(2) not null,
  d_day   NUMBER(2) not null);
comment on table T_BAS_CALENDAR  is '日历表';
comment on column T_BAS_CALENDAR.d_year  is '年';
comment on column T_BAS_CALENDAR.d_month  is '月';
comment on column T_BAS_CALENDAR.d_day  is '日';alter table T_BAS_CALENDAR  add constraint PK_BAS_CALENDAR primary key (D_YEAR, D_MONTH, D_DAY);

但是如何向这张表批量插入日历数据,方法就很多了,下面是仅用SQL语言生成日历的参考方法:

 1 create or replace procedure P_IMPORT_CALENDAR(p_year_start number,
 2                                               p_year_end   number) is
 3   cmonth    integer;
 4   cyear     integer;
 5   cday      integer;
 6   day_first integer;
 7   day_last  integer;
 8 begin
 9   --生成从p_year_start到p_year_end的所有日历 created by yjmyzz@126.com 2015-04-27
10   
11   --firstly,delete history records
12   delete from T_BAS_CALENDAR where d_year between p_year_start and p_year_end;
13   for cyear in p_year_start .. p_year_end loop
14     for cmonth in 1 .. 12 loop
15       --get first-day of Month
16       select to_number(cyear || lpad(cmonth, 2, '0') || '01', '99999999')
17         into day_first
18         from dual;
19       --last-day of Month
20       select to_number(to_char(add_months(to_date(day_first, 'yyyyMMdd'), 1) - 1,
21                                'yyyyMMdd'),
22                        '99999999')
23         into day_last
24         from dual;
25       for cday in day_first .. day_last loop   
26         --insert to table  
27         INSERT INTO T_BAS_CALENDAR
28           (D_YEAR, D_MONTH, D_DAY)
29         VALUES
30           (CYEAR, CMONTH, SUBSTR(cday, 7));
31       end loop;
32     end loop;
33   end loop;
34   commit;
35 end P_IMPORT_CALENDAR;


 

   

本文由职坐标整理并发布,希望对同学们学习Oracle有所帮助,更多内容请关注职坐标数据库Oracle数据库频道!


本文由 @小标 发布于职坐标。未经许可,禁止转载。
喜欢 | 0 不喜欢 | 0
看完这篇文章有何感觉?已经有0人表态,0%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程