我有一个数据库表,它有一个唯一的约束(唯一(DADSNBR,DAROLEID)对).我将同时在这个表中插入多个值,所以我想使用一个查询完成它 – 我假设这将是更快的方式.我的查询是这样的:
INSERT ALL INTO ACCESS (DADSNBR,DAROLEID) VALUES (68,1) INTO ACCESS (DADSNBR,2) INTO ACCESS (DADSNBR,3) INTO ACCESS (DADSNBR,4) SELECT 1 FROM DUAL
由于语句中的某些条目与数据库中已存在的条目重复,因此整个插入失败并且未插入任何行.
有没有办法忽略唯一约束失败的情况,只需插入唯一的那些,而不必将其拆分成单独的INSERT语句?
编辑:我意识到我可能不想这样做,但我仍然很好奇它是否可能.
在Oracle中,语句要么完全成功要么完全失败(它们是原子的).但是,您可以在某些情况下添加子句来记录异常而不是引发错误:
原文链接:https://www.f2er.com/oracle/205151.html>使用BULK COLLECT – SAVE EXCEPTIONS,如this thread on askTom所示,
>或使用DBMS_ERRLOG
(我认为10g以后可用).
sql> CREATE TABLE test (pk1 NUMBER,2 pk2 NUMBER,3 CONSTRAINT pk_test PRIMARY KEY (pk1,pk2)); Table created. sql> /* Statement fails because of duplicate */ sql> INSERT into test (SELECT 1,1 FROM dual CONNECT BY LEVEL <= 2); ERROR at line 1: ORA-00001: unique constraint (VNZ.PK_TEST) violated sql> BEGIN dbms_errlog.create_error_log('TEST'); END; 2 / PL/sql procedure successfully completed. sql> /* Statement succeeds and the error will be logged */ sql> INSERT into test (SELECT 1,1 FROM dual CONNECT BY LEVEL <= 2) 2 LOG ERRORS REJECT LIMIT UNLIMITED; 1 row(s) inserted. sql> select ORA_ERR_MESG$,pk1,pk2 from err$_test; ORA_ERR_MESG$ PK1 PK2 --------------------------------------------------- --- --- ORA-00001: unique constraint (VNZ.PK_TEST) violated 1 1
您可以将LOG ERROR子句与INSERT ALL一起使用(感谢@Alex Poole),但您必须在每个表之后添加子句:
sql> INSERT ALL 2 INTO test VALUES (1,1) LOG ERRORS REJECT LIMIT UNLIMITED 3 INTO test VALUES (1,1) LOG ERRORS REJECT LIMIT UNLIMITED 4 (SELECT * FROM dual); 0 row(s) inserted.