前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >oracle:如何用sql生成日历

oracle:如何用sql生成日历

作者头像
菩提树下的杨过
发布2018-01-19 10:59:57
1.4K0
发布2018-01-19 10:59:57
举报

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

代码语言:javascript
复制
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语言生成日历的参考方法:

代码语言:javascript
复制
 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;
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-04-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
数据库
云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档