PL/SQL开发人员如何获取导致插入失败的行?

and*_*dre 5 sql oracle

我正在做一个插入到具有唯一列的表中的方法.我不知道的是,我是否可以访问使插入失败的插入值.

例如:

table1(id,name, phone);

name is unique.

insert (1,a,123);

insert (2,a,1234);
Run Code Online (Sandbox Code Playgroud)

我想要的是当我做第二次插入时我返回id值'1'而不必重复查询.

先感谢您.

Nic*_*nov 5

从oracle 10g r2开始,您可以使用insert命令的log errors子句在单独的表中记录错误.这是一个例子:

SQL> create table test_table(
  2    id   number primary key,
  3    col1 varchar2(7)
  4  )
  5  ;

Table created


-- creates a table for logging errors (table name will be prefaced with err$_)
SQL> begin dbms_errlog.create_error_log('TEST_TABLE'); end;
  2  /

PL/SQL procedure successfully completed

-- violates primary key constraint
SQL> insert into test_table(id, col1)
  2  (  select 1, level
  3      from dual
  4    connect by level <= 3)
  5    log errors reject limit unlimited;

1 row inserted

SQL> commit;

SQL> select * from test_table;

        ID COL1
---------- -------
         1 1


SQL> select * from err$_test_table;

ORA_ERR_NUMBER$ ORA_ERR_MESG$                                           ORA_ERR_ROWID$  ORA_ERR_OPTYP$ ORA_ERR_TAG$ ID  COL1
--------------- ------------------------------------------------------------------------------------------------------------
              1 ORA-00001: unique constraint (HR.SYS_C008315) violated  I                                            1     2
              1 ORA-00001: unique constraint (HR.SYS_C008315) violated  I                                            1     3
Run Code Online (Sandbox Code Playgroud)