oralce sql 创建指定时间段内的日历信息



-- Create table
create table TEMP_CALENDAR
(
  MONTH VARCHAR2(6),
  W_7   VARCHAR2(2),
  W_1   VARCHAR2(2),
  W_2   VARCHAR2(2),
  W_3   VARCHAR2(2),
  W_4   VARCHAR2(2),
  W_5   VARCHAR2(2),
  W_6   VARCHAR2(2),
  WEEK  VARCHAR2(20)
) ;
-- Add comments to the table 
comment on table TEMP_CALENDAR
  is '日期源数据表';
-- Add comments to the columns 
comment on column TEMP_CALENDAR.MONTH
  is '月份(格式如:200801)';
comment on column TEMP_CALENDAR.W_7
  is '周日的日期(如:06)';
comment on column TEMP_CALENDAR.W_1
  is '周一(如:07)';
comment on column TEMP_CALENDAR.W_2
  is '周二(如:08)';
comment on column TEMP_CALENDAR.W_3
  is '周三(如:09)';
comment on column TEMP_CALENDAR.W_4
  is '周四(如:10)';
comment on column TEMP_CALENDAR.W_5
  is '周五(如:11)';
comment on column TEMP_CALENDAR.W_6
  is '周六(如:12)';
comment on column TEMP_CALENDAR.WEEK
  is '本月第几周';
----生成 日历信息 
-- truncate table calendar; 
declare 


    vi_begin_year number(6); 
    vi_end_year number(6); 
    vi_year number(6); 
    vi_month number(6); 
    vs_month varchar2(6); 
    vs_first_day varchar2(8); 




begin 


    vi_begin_year :=2000; ---start year
    vi_end_year :=2100;   --- end year
    vi_month :=1; 
    vi_year := vi_begin_year; 


loop exit when(vi_year > vi_end_year);
 for i in 1..12 loop 
     if length(i) =1 then 
        vs_month := to_char(vi_year)||'0'||to_char(i); 
     else
         vs_month := to_char(vi_year)||to_char(i); 
     end if;
     
  vs_first_day := vs_month||'01'; 
  
  insert into temp_calendar ( month, week,w_7, w_1, w_2, w_3, w_4, w_5, w_6 ) 
  
  select substr(vs_first_day,1,6) month, 
  ceil((to_char(everyday,'dd')+(to_char(to_date(vs_first_day,'yyyymmdd'),'d')-1))/7) as week, 
  sum(decode(to_char(everyday,'dy'),'星期日',to_char(everyday,'dd'))) as 星期日, 
  sum(decode(to_char(everyday,'dy'),'星期一',to_char(everyday,'dd'))) as 星期一, 
  sum(decode(to_char(everyday,'dy'),'星期二',to_char(everyday,'dd'))) as 星期二, 
  sum(decode(to_char(everyday,'dy'),'星期三',to_char(everyday,'dd'))) as 星期三, 
  sum(decode(to_char(everyday,'dy'),'星期四',to_char(everyday,'dd'))) as 星期四, 
  sum(decode(to_char(everyday,'dy'),'星期五',to_char(everyday,'dd'))) as 星期五, 
  sum(decode(to_char(everyday,'dy'),'星期六',to_char(everyday,'dd'))) as 星期六 
  from(
    select to_date(vs_first_day,'yyyymmdd') + level - 1 as everyDay 
    from dual 
    connect by level <= (last_day(to_date(vs_first_day,'yyyymmdd')) 
    - to_date(vs_first_day,'yyyymmdd') +1) ) 
  group by ceil((to_char(everyday,'dd')+(to_char(to_date(vs_first_day,'yyyymmdd'),'d')-1))/7) ; 
  
  
  commit; 
  
  end loop; 
  
  vi_year := vi_year+1; 
  
end loop; 
  
  end;
  order by a.year,a.month, a.week;
原文地址:https://www.cnblogs.com/lytwajue/p/6958372.html