2011-08-15 50 views
2

我有以下合併過程。如何從MERGE語句訪問值在異常處理部分...訪問合併語句中的值

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; 

回答

4

根據不同的Oracle版本,你可以使用DML錯誤記錄。沿

東西線與數據

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. 

與錯誤日誌語法

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

PL/SQL procedure successfully completed. 

MERGE創建錯誤日誌表創建源&目標表

請注意,一行成功合併,而一行生成唯一約束異常並寫入錯誤表。

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

太棒了,非常感謝! – Asterisk

+0

你知道是否有SQL%...選項來知道是否有任何錯誤?或者我必須查詢err $表? – ShoeLace

+0

沒關係..沒有.. http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/sql_cursor.htm – ShoeLace