oracle exchange partition
Exchange partition提供了一种方式,让你在表与表或分区与分区之间迁移数据,注意不是将表转换成分区或非分区的形式,而仅只是迁移表中数据(互相迁移),由于其号称是采用了更改数据字典的方式,因此效率最高(几乎不涉及io操作)。Exchange partition适用于所有分区格式,你可以将数据从分区表迁移到非分区表,也可以从非分区表迁移至分区表,但不支持range partition 和range partition之间交换。
示例:
SQL> CREATE TABLE ou_a (a INTEGER)
2 PARTITION BY RANGE(a)
3 (PARTITION p1 VALUES LESS THAN (5),
4 PARTITION p2 VALUES LESS THAN (6),
5 PARTITION p3 VALUES LESS THAN (7),
6 PARTITION p4 VALUES LESS THAN (8),
7 PARTITION p5 VALUES LESS THAN (9)
8 );
Table created
SQL> insert into ou_a values(5);
1 row inserted
SQL> insert into ou_a values(6);
1 row inserted
SQL> insert into ou_a values(7);
1 row inserted
SQL> insert into ou_a values(8);
1 row inserted
SQL> commit;
Commit complete
SQL> create index index_ou on ou_a(a) local;
Index created
SQL> create table ou_temp (a integer);
Table created
SQL> insert into ou_temp values(8);
1 row inserted
SQL> commit;
Commit complete
SQL> alter table ou_a exchange partition p2 with table ou_temp;
alter table ou_a exchange partition p2 with table ou_temp
ORA-14099: 未对指定分区限定表中的所有行
此处说明当交换分区表时,临时表的数据分区键值超出分区的临界值时会报ORA-14099错误,如需要屏蔽该错误,则需使用Without validation,如下:
SQL> alter table ou_a exchange partition p2 with table ou_temp without validation;
Table altered
SQL> select a.Partition_Name, a.status from User_Ind_Partitions a where a.Index_Name = 'INDEX_OU';
PARTITION_NAME STATUS
------------------------------ --------
P1 USABLE
P2 UNUSABLE
P3 USABLE
P4 USABLE
此时查看索引状态会发现,交换分区后本地索引在分区p2里失效,变为不可用,说明在exchange partition时有可能会造成索引失效的问题。
SQL> select * from ou_a where a=8;
A
--------------------
8
SQL> select * from ou_a;
A
--------------------
8
6
7
8
当索引失效时,查看全表是可以查到两条为8的数据,而走where a=8时确只能查到一条数据。这是因为where a=8时,oracle通过分区修剪去找分区p5,而此时因为8的两个值一个存储在p2一个存储在p5,所以说当使用without validation时会造成很多无效的数据,同时亦会造成索引失效的问题。
那如何保证索引不失效勒,oracle提供了一个参数including indexes,可保证交换分区后索引是有效的。如下:
SQL> CREATE TABLE ou_a (a INTEGER)
2 PARTITION BY RANGE(a)
3 (PARTITION p1 VALUES LESS THAN (5),
4 PARTITION p2 VALUES LESS THAN (6),
5 PARTITION p3 VALUES LESS THAN (7),
6 PARTITION p4 VALUES LESS THAN (8),
7 PARTITION p5 VALUES LESS THAN (9)
8 );
Table created
SQL> insert into ou_a values(5);
1 row inserted
SQL> insert into ou_a values(6);
1 row inserted
SQL> insert into ou_a values(7);
1 row inserted
SQL> insert into ou_a values(8);
1 row inserted
SQL> commit;
Commit complete
SQL> create index index_ou on ou_a(a) local;
Index created
SQL> create table ou_temp (a integer);
Table created
SQL> create index index_temp on ou_temp(a);
Index created
SQL> insert into ou_temp values(8);
1 row inserted
SQL> commit;
Commit complete
SQL> alter table ou_a exchange partition p2 with table ou_temp including indexes without validation;
Table altered
SQL> select status from User_Ind_Partitions a where a.Index_Name = 'INDEX_OU';
STATUS
--------
USABLE
USABLE
USABLE
USABLE
USABLE
此时发现索引交换过来了,说明including indexes可以将索引交换过来。