1. 程式人生 > >使用ORACLE線上重定義將普通表改為分割槽表

使用ORACLE線上重定義將普通表改為分割槽表

1.首先建立測試表,並插入測試資料:

create table myPartition(id number,code varchar2(5),identifier varchar2(20));
insert into myPartition values(1,'01','01-01-0001-000001');
insert into myPartition values(2,'02','02-01-0001-000001');
insert into myPartition values(3,'03','03-01-0001-000001');
insert into myPartition values(4,'04','04-01-0001-000001');
commit;
alter table myPartition add constraint pk_test_id primary key (id);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

2.檢查下這張表是否可以線上重定義,無報錯表示可以,報錯會給出錯誤資訊:

--管理員許可權執行begin
SQL> exec dbms_redefinition.can_redef_table('scott', 'myPartition');
PL/SQL procedure successfully completed
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

–管理員許可權執行end

3.建立線上重定義需要的中間表,表結構就是要將原測試表重定義成什麼樣子,這裡建立的是按全宗號分割槽的分割槽表:

create table t_temp(id number,code varchar2(5),
identifier varchar2(20)) partition by range(id)(  
          partition TAB_PARTOTION_01 values less than (2),  
          partition TAB_PARTOTION_02 values less than (3),  
          partition TAB_PARTOTION_03 values less than (4),  
          partition TAB_PARTOTION_04 values
less than (5), partition TAB_PARTOTION_OTHER values less THAN (MAXVALUE) );
alter table t_temp add constraint pk_temp_id2 primary key (id);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

4.啟動線上重定義:

--管理員許可權執行sql命令列執行
exec dbms_redefinition.start_redef_table('scott', 'myPartition', 't_temp');
--管理員許可權執行sql命令列執行
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

這裡dbms_redefinition包的start_redef_table模組有3個引數,分別是SCHEMA名字、原表的名字、中間表的名字。

5.啟動線上重定義後,中間表就可以查到原表的資料。

select * from t_temp;
  • 1
  • 1

6.由於在生成系統中,線上重定義的過程中原資料表可能會發生資料改變,向原表中插入資料模擬資料改變。

insert into myPartition values(5,'05','05-01-0001-000001');
commit;
  • 1
  • 2
  • 1
  • 2

7.此時原表被修改,中間表並沒有更新。

select * from myPartition;
select * from t_temp;
  • 1
  • 2
  • 1
  • 2

8.使用dbms_redefinition包的sync_interim_table模組重新整理資料後,中間表也可以看到資料更改

--管理員許可權執行sql命令列執行,同步兩邊資料
exec dbms_redefinition.sync_interim_table('scott', 'myPartition', 't_temp');
--管理員許可權執行sql命令列執行
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

查詢同步後的兩邊資料是否一致:

select * from myPartition;
select * from t_temp;
  • 1
  • 2
  • 1
  • 2

9.結束線上重定義

--管理員許可權執行sql命令列執行,結束重定義
exec dbms_redefinition.finish_redef_table('scott', 'myPartition', 't_temp');
--管理員許可權執行sql命令列執行
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

10.驗證資料

select * from myPartition;
select * from t_temp;
  • 1
  • 2
  • 1
  • 2

11.檢視各分割槽資料是否正確

select table_name, partition_name from user_tab_partitions where table_name = 'myPartition';

select * from myPartition partition(TAB_PARTOTION_01);
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

12.線上重定義後,中間表已經沒有意義,刪掉中間表


drop table t_temp purge;