开发者

accessing values in merge statement

I h开发者_JAVA技巧ave the following merge procedure. How can I access values from merge statement in exception handling part...

procedure merge_students
is 
begin
        merge into
              students a
            using
              studentstmp t
            on
              (a.code = t.code)
            when matched then update set a.name = t.name,

            when not matched then insert (code,name)
                                  values (t.code,t.name);
            EXCEPTION
                 WHEN DUP_VAL_ON_INDEX THEN
                    dbms_output.put_line('students code: ' || a.code); //how to access a.code here
                    dbms_output.put_line('studentsTMP code: ' || t.code); // and t.code here
end;


Depending on the Oracle version, you could use DML error logging. Something along the lines of

Create the Source & Destination Tables with Data

SQL> create table foo (
  2    col1 number primary key,
  3    col2 number unique
  4  );

Table created.

SQL> create table foo_temp (
  2    col1 number,
  3    col2 number
  4  );

Table created.

SQL> insert into foo values( 1, 1 );

1 row created.

SQL> insert into foo_temp values( 2, 1 );

1 row created.

SQL> insert into foo_temp values( 3, 2 );

1 row created.

Create the Error Log Table

SQL> exec dbms_errlog.create_error_log( 'FOO' );

PL/SQL procedure successfully completed.

MERGE with the LOG ERRORS syntax

Note that one row was sucessfully merged while one row generated a unique constraint exception and was written to the error table.

SQL> merge into foo
  2    using foo_temp on (foo.col1 = foo_temp.col1)
  3   when matched then
  4      update set foo.col2 = foo_temp.col2
  5   when not matched then
  6      insert( col1, col2 )
  7        values( foo_temp.col1, foo_temp.col2 )
  8   log errors into err$_foo
  9   reject limit unlimited;

1 row merged.

SQL> select * from foo;

      COL1       COL2
---------- ----------
         1          1
         3          2

SQL> select * from foo_temp;

      COL1       COL2
---------- ----------
         2          1
         3          2

SQL> select * from err$_foo;

ORA_ERR_NUMBER$
---------------
ORA_ERR_MESG$
--------------------------------------------------------------------------------

ORA_ERR_ROWID$
--------------------------------------------------------------------------------

OR
--
ORA_ERR_TAG$
--------------------------------------------------------------------------------

COL1
--------------------------------------------------------------------------------

COL2
--------------------------------------------------------------------------------

              1
ORA-00001: unique constraint (SCOTT.SYS_C0024443) violated

I

2
1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜