ORACLE分區表轉換在線重定義DBMS_REDEFINITION

 更新時間:2022年07月07日 10:56:42   作者:Lucifer三思而后行  
這篇文章主要為大家介紹了ORACLE分區表轉換在線重定義DBMS_REDEFINITION表,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

一、DBMS_REDEFINITION(在線重定義)

參考MOS文檔:_How To Partition Existing Table Using DBMS_REDEFINITION (Doc ID 472449.1)  _

支持的數據庫版本:Oracle Database - Enterprise Edition - Version 9.2.0.4 and later

在線重定義是通過 物化視圖 實現的。

使用在線重定義的一些限制條件:

  • 1、必須有足夠的表空間來容納表的兩倍數據量。
  • 2、主鍵列不能被修改。
  • 3、表必須有主鍵。
  • 4、必須在同一個用戶下進行在線重定義。
  • 5、SYS和SYSTEM用戶下的表無法進行在線重定義。
  • 6、在線重定義無法采用nologging。
  • 7、如果中間表有新增列,則不能有NOT NULL約束

DBMS_REDEFINITION包:

  • ABSORT_REDEF_TABLE:清理重定義的錯誤和中止重定義;
  • CAN_REDEF_TABLE:檢查表是否可以進行重定義,存儲過程執行成功代表可以進行重定義;
  • COPY_TABLE_DEPENDENTS:同步索引和依賴的對象(包括索引、約束、觸發器、權限等);
  • FINISH_REDEF_TABLE:完成在線重定義;
  • REGISTER_DEPENDENTS_OBJECTS:注冊依賴的對象,如索引、約束、觸發器等;
  • START_REDEF_TABLE:開始在線重定義;
  • SYNC_INTERIM_TABLE:增量同步數據;
  • UNREGISTER_DEPENDENT_OBJECT:不注冊依賴的對象,如索引、約束、觸發器等;
CREATE OR REPLACE PACKAGE SYS.dbms_redefinition AUTHID CURRENT_USER IS
  ------------
  --  OVERVIEW
  --
  -- This package provides the API to perform an online, out-of-place
  -- redefinition of a table
  --- =========
  --- CONSTANTS
  --- =========
  -- Constants for the options_flag parameter of start_redef_table
  cons_use_pk    CONSTANT PLS_INTEGER := 1;
  cons_use_rowid CONSTANT PLS_INTEGER := 2;
  -- Constants used for the object types in the register_dependent_object
  cons_index      CONSTANT PLS_INTEGER := 2;
  cons_constraint CONSTANT PLS_INTEGER := 3;
  cons_trigger    CONSTANT PLS_INTEGER := 4;
  cons_mvlog      CONSTANT PLS_INTEGER := 10;
  -- constants used to specify the method of copying indexes
  cons_orig_params CONSTANT PLS_INTEGER := 1;
  PRAGMA SUPPLEMENTAL_LOG_DATA(default, AUTO_WITH_COMMIT);
  -- NAME:     can_redef_table - check if given table can be re-defined
  -- INPUTS:   uname        - table owner name
  --           tname        - table name
  --           options_flag - flag indicating user options to use
  --           part_name    - partition name
  PROCEDURE can_redef_table(uname        IN VARCHAR2,
                            tname        IN VARCHAR2,
                            options_flag IN PLS_INTEGER := 1,
                            part_name    IN VARCHAR2 := NULL);
  PRAGMA SUPPLEMENTAL_LOG_DATA(can_redef_table, NONE);
  -- NAME:     start_redef_table - start the online re-organization
  -- INPUTS:   uname        - schema name
  --           orig_table   - name of table to be re-organized
  --           int_table    - name of interim table
  --           col_mapping  - select list col mapping
  --           options_flag - flag indicating user options to use
  --           orderby_cols - comma separated list of order by columns
  --                          followed by the optional ascending/descending
  --                          keyword
  --           part_name    - name of the partition to be redefined
  PROCEDURE start_redef_table(uname        IN VARCHAR2,
                              orig_table   IN VARCHAR2,
                              int_table    IN VARCHAR2,
                              col_mapping  IN VARCHAR2 := NULL,
                              options_flag IN BINARY_INTEGER := 1,
                              orderby_cols IN VARCHAR2 := NULL,
                              part_name    IN VARCHAR2 := NULL);
  -- NAME:     finish_redef_table - complete the online re-organization
  -- INPUTS:   uname        - schema name
  --           orig_table   - name of table to be re-organized
  --           int_table    - name of interim table
  --           part_name    - name of the partition being redefined
  PROCEDURE finish_redef_table(uname          IN VARCHAR2,
                               orig_table     IN VARCHAR2,
                               int_table      IN VARCHAR2,
                               part_name      IN VARCHAR2 := NULL);
  -- NAME:     abort_redef_table - clean up after errors or abort the
  --                               online re-organization
  -- INPUTS:   uname        - schema name
  --           orig_table   - name of table to be re-organized
  --           int_table    - name of interim table
  --           part_name    - name of the partition being redefined
  PROCEDURE abort_redef_table(uname        IN VARCHAR2,
                              orig_table   IN VARCHAR2,
                              int_table    IN VARCHAR2,
                              part_name    IN VARCHAR2 := NULL);
  -- NAME:     sync_interim_table - synchronize interim table with the original
  --                                table
  -- INPUTS:   uname        - schema name
  --           orig_table   - name of table to be re-organized
  --           int_table    - name of interim table
  --           part_name    - name of the partition being redefined
  PROCEDURE sync_interim_table(uname       IN VARCHAR2,
                               orig_table  IN VARCHAR2,
                               int_table   IN VARCHAR2,
                               part_name   IN VARCHAR2 := NULL);
  -- NAME:     register_dependent_object - register dependent object
  --
  -- INPUTS:   uname        - schema name
  --           orig_table   - name of table to be re-organized
  --           int_table    - name of interim table
  --           dep_type     - type of the dependent object
  --           dep_owner    - name of the dependent object owner
  --           dep_orig_name- name of the dependent object defined on table
  --                          being re-organized
  --           dep_int_name - name of the corressponding dependent object on
  --                          the interim table
  PROCEDURE register_dependent_object(uname         IN VARCHAR2,
                                      orig_table    IN VARCHAR2,
                                      int_table     IN VARCHAR2,
                                      dep_type      IN PLS_INTEGER,
                                      dep_owner     IN VARCHAR2,
                                      dep_orig_name IN VARCHAR2,
                                      dep_int_name  IN VARCHAR2);
  -- NAME:     unregister_dependent_object - unregister dependent object
  --
  -- INPUTS:   uname        - schema name
  --           orig_table   - name of table to be re-organized
  --           int_table    - name of interim table
  --           dep_type     - type of the dependent object
  --           dep_owner    - name of the dependent object owner
  --           dep_orig_name- name of the dependent object defined on table
  --                          being re-organized
  --           dep_int_name - name of the corressponding dependent object on
  --                          the interim table
  PROCEDURE unregister_dependent_object(uname         IN VARCHAR2,
                                        orig_table    IN VARCHAR2,
                                        int_table     IN VARCHAR2,
                                        dep_type      IN PLS_INTEGER,
                                        dep_owner     IN VARCHAR2,
                                        dep_orig_name IN VARCHAR2,
                                        dep_int_name  IN VARCHAR2);
  --  NAME:     copy_table_dependents
  --
  --  INPUTS:  uname             - schema name
  --           orig_table        - name of table to be re-organized
  --           int_table         - name of interim table
  --           copy_indexes      - integer value indicating whether to
  --                               copy indexes
  --                               0 - don't copy
  --                               1 - copy using storage params/tablespace
  --                                   of original index
  --           copy_triggers      - TRUE implies copy triggers, FALSE otherwise
  --           copy_constraints   - TRUE implies copy constraints, FALSE
  --                                otherwise
  --           copy_privileges    - TRUE implies copy privileges, FALSE
  --                                otherwise
  --           ignore errors      - TRUE implies continue after errors, FALSE
  --                                otherwise
  --           num_errors         - number of errors that occurred while
  --                                cloning ddl
  --           copy_statistics    - TRUE implies copy table statistics, FALSE
  --                                otherwise.
  --                                If copy_indexes is 1, copy index
  --                                related statistics, 0 otherwise.
  --           copy_mvlog         - TRUE implies copy table's MV log, FALSE
  --                                otherwise.
  PROCEDURE copy_table_dependents(uname              IN  VARCHAR2,
                                  orig_table         IN  VARCHAR2,
                                  int_table          IN  VARCHAR2,
                                  copy_indexes       IN  PLS_INTEGER := 1,
                                  copy_triggers      IN  BOOLEAN := TRUE,
                                  copy_constraints   IN  BOOLEAN := TRUE,
                                  copy_privileges    IN  BOOLEAN := TRUE,
                                  ignore_errors      IN  BOOLEAN := FALSE,
                                  num_errors         OUT PLS_INTEGER,
                                  copy_statistics    IN  BOOLEAN := FALSE,
                                  copy_mvlog         IN  BOOLEAN := FALSE);
END;

二、在線重定義表的步驟

1.創建未分區的表

創建未分區的表,如果存在,就不需要操作。

--前置準備:創建用戶,表空間,授權用戶。
SQL> create tablespace PARTITION;
SQL> create user par identified by par;
SQL> grant dba to par;
--創建表,索引,授權,同義詞
SQL> conn par/par
Connected.
-- Create table
create table student(
s_id number(8) PRIMARY KEY,
s_name varchar2(20) not null,
s_sex varchar2(8),
s_birdate date,
constraint u_1 unique(s_name),
constraint c_1 check (s_sex in ('MALE','FEMALE')))
tablespace PARTITION;
-- Add comments to the table 
comment on table STUDENT is '學生表';
-- Add comments to the columns 
comment on column STUDENT.s_name is '姓名';
comment on column STUDENT.s_sex is '性別';
comment on column STUDENT.s_birdate is '出生日期';
-- Create/Recreate indexes 
create index S_NAME_IDX on STUDENT (S_NAME, S_SEX) tablespace PARTITION;
-- Create SYNONYM
CREATE SYNONYM stu FOR student;
-- Grant/Revoke object privileges 
grant select, insert, delete on STUDENT to SCOTT;
--查看表結構
SQL> desc stu
 Name					   Null?    Type
 ----------------------------------------- -------- ----------------------------
 S_ID					   NOT NULL NUMBER(8)
 S_NAME 				   NOT NULL VARCHAR2(20)
 S_SEX						    VARCHAR2(8)
 S_BIRDATE					    DATE
--插入數據
begin
  for i in 0 .. 24 loop
    insert into student values
      (i,
       'student_' || i,
       decode(mod(i, 2), 0, 'MALE', 'FEMALE'),
       add_months(to_date('2019-1-1', 'yyyy-mm-dd'), i));
  end loop;
  commit;
end;
/

2.確認表是否存在主鍵,表空間是否足夠,收集表統計信息。

--查看表主鍵
SQL> select cu.* from user_cons_columns cu, user_constraints au where cu.constraint_name = au.constraint_name and au.constraint_type = 'P' and au.table_name = 'STUDENT';
--查看表大小和表空間
--查看表空間
SQL> select tablespace_name from dba_segments where segment_type= 'TABLE' and segment_name='STUDENT' and owner='PAR';
--查看表大小
SQL> select sum(bytes/1024/1024) from dba_segments where segment_type= 'TABLE' and segment_name='STUDENT' and owner='PAR';
--查看表空間
select tbs_used_info.tablespace_name,
       tbs_used_info.alloc_mb,
       tbs_used_info.used_mb,
       tbs_used_info.max_mb,
       tbs_used_info.free_of_max_mb,
       tbs_used_info.used_of_max || '%' used_of_max_pct
  from (select a.tablespace_name,
               round(a.bytes_alloc / 1024 / 1024) alloc_mb,
               round((a.bytes_alloc - nvl(b.bytes_free,
                                          0)) / 1024 / 1024) used_mb,
               round((a.bytes_alloc - nvl(b.bytes_free,
                                          0)) * 100 / a.maxbytes) used_of_max,
               round((a.maxbytes - a.bytes_alloc + nvl(b.bytes_free,
                                                       0)) / 1048576) free_of_max_mb,
               round(a.maxbytes / 1048576) max_mb
          from (select f.tablespace_name,
                       sum(f.bytes) bytes_alloc,
                       sum(decode(f.autoextensible,
                                  'YES',
                                  f.maxbytes,
                                  'NO',
                                  f.bytes)) maxbytes
                  from dba_data_files f
                 group by tablespace_name) a,
               (select f.tablespace_name,
                       sum(f.bytes) bytes_free
                  from dba_free_space f
                 group by tablespace_name) b
         where a.tablespace_name = b.tablespace_name(+)) tbs_used_info
 order by tbs_used_info.used_of_max desc;
--如果表空間不夠,提前增加表空間大小
alter tablespace PARTITION add datafile;
--收集統計信息(可忽略)
EXEC DBMS_STATS.gather_table_stats('PAR', 'STUDENT', cascade => TRUE);

3.調用DBMS_REDEFINITION.CAN_REDEF_TABLE()

調用DBMS_REDEFINITION.CAN_REDEF_TABLE()過程,確認表是否滿足重定義的條件。

SQL> EXEC Dbms_Redefinition.can_redef_table('PAR', 'STUDENT');
PL/SQL procedure successfully completed.

4.建立一個空的中間表

在用一個用戶中建立一個空的中間表,根據重定義后你期望得到的結構建立中間表。比如:采用分區表(間隔分區),增加了COLUMN等。

在中間表上建立觸發器、索引和約束,并進行相應的授權。任何包含中間表的完整性約束應將狀態置為disabled。(此步驟也可以放在同步數據后操作)

--創建間隔分區(增加列s_phone)
create table STUDENT_PAR
(
  s_id      NUMBER(8) not null,
  s_name    VARCHAR2(20) not null,
  s_sex     VARCHAR2(8),
  s_birdate DATE,
  s_phone   number
)
tablespace PARTITION
PARTITION BY RANGE(s_birdate)
INTERVAL (NUMTOYMINTERVAL(1,'MONTH')) STORE IN (partition)
(PARTITION STUDENT_201901 VALUES LESS THAN (TO_DATE('2019-02-01 00:00:00', 'SYYYY-MM-DD Hh34:MI:SS', 'NLS_CALENDAR=GREGORIAN')));
--臨時中間表上創建如下:
--創建主鍵約束
alter table STUDENT_PAR add primary key (S_ID) using index tablespace PARTITION;
--創建唯一索引約束
alter table STUDENT_PAR add constraint U_1_PAR unique (S_NAME) using index tablespace PARTITION;
--創建check約束
alter table STUDENT_PAR add constraint C_1_PAR check (s_sex in ('MALE','FEMALE'));
--創建索引
CREATE INDEX S_NAME_IDX_PAR ON STUDENT_PAR (S_NAME,S_SEX) tablespace PARTITION;
--創建同義詞
CREATE SYNONYM stu_par FOR STUDENT_PAR;
--添加描述
COMMENT ON TABLE  STUDENT_PAR IS '學生表';
COMMENT ON COLUMN STUDENT_PAR.s_name IS '姓名';
COMMENT ON COLUMN STUDENT_PAR.s_sex IS '性別';
COMMENT ON COLUMN STUDENT_PAR.s_birdate IS '出生日期';
--授權
GRANT SELECT,INSERT,DELETE ON STUDENT_PAR TO scott; 

5.調用DBMS_REDEFINITION.START_REDEF_TABLE

調用DBMS_REDEFINITION.START_REDEF_TABLE()過程,并提供下列參數:被重定義的表的名稱、中間表的名稱、列的映射規則、重定義方法。

如果映射方法沒有提供,則認為所有包括在中間表中的列用于表的重定義。如果給出了映射方法,則只考慮映射方法中給出的列。如果沒有給出重定義方法,則默認使用主鍵方式。

SQL> BEGIN
DBMS_REDEFINITION.start_redef_table(
uname => 'PAR', 
orig_table => 'STUDENT',
int_table => 'STUDENT_PAR');
END;
/
PL/SQL procedure successfully completed.

6.(可選)在創建索引之前將新表與臨時名稱同步

Notes:如果在執行DBMS_REDEFINITION.START_REDEF_TABLE()過程和執行DBMS_REDEFINITION.FINISH_REDEF_TABLE()過程直接在重定義表上執行了大量的DML操作,那么可以選擇執行一次或多次的SYNC_INTERIM_TABLE()過程,此操作可以減少最后一步執行FINISH_REDEF_TABLE()過程時的鎖定時間。

--模擬業務不停,DML表數據寫入
insert into STUDENT values(25,'student_25','MALE',to_date('2020-8-1', 'yyyy-mm-dd'));
update student set s_sex='FEMALE' where s_id = 20;
commit;
--比對student和student_par數據
select s_id,s_name,s_sex,s_birdate from student
minus
select s_id,s_name,s_sex,s_birdate from student_par;
      S_ID S_NAME		S_SEX	 S_BIRDATE
---------- -------------------- -------- ------------------
	20 student_20		FEMALE	 01-SEP-20
	25 student_25		MALE	 01-AUG-20
--同步數據到臨時表
BEGIN
dbms_redefinition.sync_interim_table(
uname => 'PAR', 
orig_table => 'STUDENT',
int_table => 'STUDENT_PAR');
END;
/
--數據已全部同步到臨時表
select s_id,s_name,s_sex,s_birdate from student
minus
select s_id,s_name,s_sex,s_birdate from student_par;
no rows selected

7.執行DBMS_REDEFINITION.FINISH_REDEF_TABLE

執行DBMS_REDEFINITION.FINISH_REDEF_TABLE()過程完成表的重定義。這個過程中,原始表會被獨占模式鎖定一小段時間,具體時間和表的數據量有關。

執行完FINISH_REDEF_TABLE()過程后,原始表重定義后具有了中間表的屬性、索引、約束、授權和觸發器。中間表上disabled的約束在原始表上處于enabled狀態。

--收集par table的統計信息
EXEC DBMS_STATS.gather_table_stats('PAR', 'STUDENT_PAR', cascade => TRUE);
--結束在線重定義過程
BEGIN
dbms_redefinition.finish_redef_table(
uname => 'PAR', 
orig_table => 'STUDENT',
int_table => 'STUDENT_PAR');
END;
/
SQL> select table_name,PARTITION_NAME from user_tab_partitions where table_name in ('STUDENT','STUDENT_PAR');
SQL> select table_name,index_name from user_indexes where table_name in ('STUDENT','STUDENT_PAR');

此時,臨時表(及其索引)已成為“真實”表,并且它們的名稱已在名稱詞典中切換。

8.重命名所有約束和索引以匹配原始名稱

--drop中間表或者rename原來的約束
a.drop table STUDENT_PAR;
b.
ALTER TABLE STUDENT_PAR RENAME CONSTRAINT U_1 TO U_1_20210411;
ALTER TABLE STUDENT_PAR RENAME CONSTRAINT C_1 TO C_1_20210411;
ALTER INDEX S_NAME_IDX RENAME TO S_NAME_IDX_20210411;
ALTER INDEX U_1 RENAME TO U_1_20210411;
--rename 新分區表的約束和索引
ALTER TABLE STUDENT RENAME CONSTRAINT U_1_PAR TO U_1;
ALTER TABLE STUDENT RENAME CONSTRAINT C_1_PAR TO C_1;
ALTER INDEX S_NAME_IDX_PAR RENAME TO S_NAME_IDX;
ALTER INDEX U_1_PAR RENAME TO U_1;
--查看索引,約束名稱是否正確
select table_name,index_name from user_indexes where table_name in ('STUDENT','STUDENT_PAR') order by table_name;
TABLE_NAME		       INDEX_NAME
------------------------------ ------------------------------
STUDENT 		       S_NAME_IDX
STUDENT 		       SYS_C0011401
STUDENT 		       U_1
STUDENT_PAR		       S_NAME_IDX_20210411
STUDENT_PAR		       U_1_20210411
STUDENT_PAR		       SYS_C0011395
SQL> desc stu
 Name					   Null?    Type
 ----------------------------------------- -------- ----------------------------
 S_ID					   NOT NULL NUMBER(8)
 S_NAME 				   NOT NULL VARCHAR2(20)
 S_SEX						    VARCHAR2(8)
 S_BIRDATE					    DATE
 S_PHONE					    NUMBER

以上就是ORACLE分區表轉換在線重定義DBMS_REDEFINITION的詳細內容,更多關于ORACLE分區表轉換在線重定義的資料請關注腳本之家其它相關文章!

相關文章

最新評論

美丽人妻被按摩中出中文字幕