|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?注册账号
×
转贴:Oracle动态添加分区
存储过程:
- create or replace procedure manage_table_partitions(
- tname varchar2,
- curDate date
- ) is
- IS_PART_EXISTS integer := 0;
- IS_TABLE_EXISTS integer := 0;
- IS_PART_TABLE integer := 0;
- P_LABEL varchar2(30) := to_char(curDate,'YYYYMMDD');
- MAX_PARTITION_DATE date;
- MIN_PARTITION_DATE date;
- TARGET_TABLE varchar2(40) := upper(trim(tname));
- V_SQL varchar2(3000) := '';
- -- 定义异常类型变量
- no_table_exception exception;
- less_than_latest_exception exception;
- -- 固定参数
- ADD_FREQ integer := 1;
- begin
- -- 查看这张表是否为分区表
- select count(*) into IS_PART_TABLE from user_part_tables
- where table_name = TARGET_TABLE;
- if IS_PART_TABLE <> 1 then
- select count(*) into IS_TABLE_EXISTS from tab where tname = TARGET_TABLE;
- if IS_TABLE_EXISTS <> 1 then
- dbms_output.put_line(tname||',这张表不存在');
- raise no_table_exception;
- end if;
- dbms_output.put_line(tname||',这张表不是分区表,将直接清空表中数据');
- V_SQL := 'truncate table ' || tname;
- execute immediate V_SQL;
- return ;
- end if;
- -- 查看分区是否存在
- select count(*) into IS_PART_EXISTS
- from user_tab_partitions
- where table_name = TARGET_TABLE
- and partition_name = 'P'||P_LABEL
- ;
- if IS_PART_EXISTS <> 1 then
-
- -- 查看分区表最大分区和最小分区
- select
- max(to_date(substr(partition_name,2),'YYYY-MM-DD'))
- ,min(to_date(substr(partition_name,2),'YYYY-MM-DD'))
- into
- MAX_PARTITION_DATE
- ,MIN_PARTITION_DATE
- from user_tab_partitions
- where table_name = TARGET_TABLE
- group by table_name;
- -- 检查准备创建的分区是否小于当前表中分区最小日期
- if MIN_PARTITION_DATE > curDate then
- dbms_output.put_Line('数据日期已经小于分区表最小日期,请重建表,重新设定最小日期分区');
- raise less_than_latest_exception;
- end if;
- dbms_output.put_line('添加分区,按照指定频率添加分区');
- MAX_PARTITION_DATE := MAX_PARTITION_DATE + ADD_FREQ;
- while MAX_PARTITION_DATE <= curDate loop
- begin
- V_SQL := 'alter table '|| tname || ' add partition P' || to_char(MAX_PARTITION_DATE,'YYYYMMDD') || ' values less than ';
- V_SQL := V_SQL || '(to_date(''' || to_char(MAX_PARTITION_DATE + ADD_FREQ,'YYYY-MM-DD') ||''',''YYYY-MM-DD''))';
- --dbms_output.put_line(V_SQL);
- execute immediate V_SQL;
- MAX_PARTITION_DATE := MAX_PARTITION_DATE + ADD_FREQ;
- end;
- end loop;
- else
- dbms_output.put_line('清除分区中的数据');
- V_SQL := 'alter table '||tname||' truncate partition P'||P_LABEL;
- dbms_output.put_line(V_SQL);
- execute immediate V_SQL;
- end if;
- end manage_table_partitions;
复制代码
|
|