忽略违反唯一约束条件的行,继续插入其它行

 以下转自:http://blog.itpub.net/18922393/viewspace-752123/ 作者:redhouser


Oracle11.2新特性之INSERT提示IGNORE_ROW_ON_DUPKEY_INDEX 


insert提示IGNORE_ROW_ON_DUPKEY_INDEX

在 insert into tablea ...select * from tableb中,如果存在唯一约束,会导致整个insert操作失败。使用IGNORE_ROW_ON_DUPKEY_INDEX提示,会忽略唯一约束冲突,回滚当前行,继续完成其他行的插入。

1,注意:
(1)如下三个提示CHANGE_DUPKEY_ERROR_INDEX, IGNORE_ROW_ON_DUPKEY_INDEX, RETRY_ON_ROW_CHANGE与其他提示不同,特别之处在于存在“语义效果(semantic effect)”。
“semantic effect”指在违反以下规则时该提示会导致错误信息:
*如果指定了索引名称,该索引必须存在且唯一;否则会导致ORA-38913错误;
*如果指定索引,必须指定一个索引。如果未指定索引,会导致ORA-38912错误;如果指定了多个索引,会导致ORA-38915错误。
*不能同时指定CHANGE_DUPKEY_ERROR_INDEX和IGNORE_ROW_ON_DUPKEY_INDEX提示;否则会导致ORA-38915错误。

(2)与其他提示相同,存在语法错误的提示将被忽略.

(3)该提示仅适用于单个表的insert操作。


2,测试:
Connected to Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 
Connected as mh@boclink
 
SQL> 
SQL> drop table test;
 
Table dropped
SQL> create table test(x int,y int);
 
Table created
SQL> insert into test values(1,1);
 
1 row inserted
SQL> insert into test values(2,2);
 
1 row inserted
SQL> insert into test values(3,3);
 
1 row inserted
SQL> commit;
 
Commit complete
SQL> create unique index uidx_test_x on test(x);
 
Index created
SQL> drop table test2;
 
Table dropped
SQL> create table test2
  2  as
  3  select * from test;
 
Table created
SQL> insert into test2 values(4,4);
 
1 row inserted
SQL> insert into test2 values(5,5);
 
1 row inserted
SQL> commit;
 
Commit complete
SQL> insert into test
  2  select * from test2;
 
insert into test
select * from test2
 
ORA-00001: 违反唯一约束条件 (MH.UIDX_TEST_X)
SQL> rollback;
 
Rollback complete
SQL> insert into test
  2  select * from test2;
 
insert into test
select * from test2
 
ORA-00001: 违反唯一约束条件 (MH.UIDX_TEST_X)
SQL> commit;
 
Commit complete
SQL> insert /*+  IGNORE_ROW_ON_DUPKEY_INDEX(test(x)) */into test
  2  select * from test2;
 
2 rows inserted
SQL> commit;
 
Commit complete
 
SQL> select * from test;
 
                                      X                                       Y
--------------------------------------- ---------------------------------------
                                      1                                       1
                                      2                                       2
                                      3                                       3
                                      4                                       4
                                      5                                       5
 
SQL>

SQL> 
SQL> insert /*+  IGNORE_ROW_ON_DUPKEY_INDEX(test,uidx_test_x) */into test
  2  select * from test2;
 
0 rows inserted
SQL> commit;
 
Commit complete


你可能感兴趣的:(忽略违反唯一约束条件的行,继续插入其它行)