2017-05-09 46 views
-3
DECLARE 
    ERROR_COUNT NUMBER; 
    errno number; 
    e_msg varchar2(50); 
    e_idx varchar2(20); 

    TYPE emp_type IS TABLE OF emp_source%ROWTYPE; 
    EMP_VAR emp_type; 

    CURSOR c1 IS SELECT * FROM emp_source; 

BEGIN 
    OPEN c1; 

    loop 
     FETCH c1 BULK COLLECT INTO EMP_VAR; 

     BEGIN 
      FORALL i in 1 .. EMP_VAR.COUNT save exceptions  
      insert INTO emp_target (e_id,e_name,sal) values (EMP_VAR(i).E_ID,EMP_VAR(i).E_NAME,EMP_VAR(i).SAL); 

      FORALL i in 1 .. EMP_VAR.COUNT save exceptions  
      insert INTO department_target (dep_name) values (EMP_VAR(i).dep_name); 

     EXCEPTION 
      WHEN others THEN 
       ERROR_COUNT := sql%bulk_exceptions.count; 

       for i in 1 .. ERROR_COUNT 
       loop 
        errno := sql%bulk_exceptions(i).error_code; 
        e_msg := sqlerrm(-errno); 
        e_idx := sql%bulk_exceptions(i).error_index; 

        insert into emp_save_exc values(errno,e_msg,e_idx); 
       end loop; 
     END; 
     exit when c1%notfound; 
    end loop; 

    close c1; 
    commit; 
END; 
+2

請參閱http://stackoverflow.com/help/how-to-ask。我試着想象一下,如果一位同事來到我的辦公桌上面打印出來並說出標題中的字眼,我會怎麼做。我的迴應可能會很短暫而且有點尖銳。 – BriteSponge

回答

2

你可以把周圍的第一FORALL一個BEGIN/END塊和處理這樣的例外:

BEGIN 
    FORALL i in 1 .. EMP_VAR.COUNT save exceptions  
    insert INTO emp_target (e_id,e_name,sal) values (EMP_VAR(i).E_ID,EMP_VAR(i).E_NAME,EMP_VAR(i).SAL); 
EXCEPTION 
    WHEN ... 
END; 

你也可以把每個塊成一個程序,讓你的代碼更有條理:

DECLARE 
    ... 
    PROCEDURE insert_emp_target (p_emp_var emp_type) IS 
    BEGIN 
     FORALL i in 1 .. EMP_VAR.COUNT save exceptions  
      insert INTO emp_target (e_id,e_name,sal) 
       values (EMP_VAR(i).E_ID,EMP_VAR(i).E_NAME,EMP_VAR(i).SAL); 
    EXCEPTION 
     WHEN ... 
    END; 

    PROCEDURE insert_dept_target (p_emp_var emp_type) IS 
    ... 
BEGIN 
    OPEN c1; 
    loop 
     FETCH c1 BULK COLLECT INTO EMP_VAR; 
     exit when c1%notfound; 
     insert_emp_target (emp_var); 
     insert_dept_target (emp_var); 
     ... 
    end loop; 
    close c1; 
    commit;  
END; 
+0

感謝您的回覆,但我知道這個場景,這是簡單的程序假設我已經在使用10插入內部,在這種情況下每個FORALL明智地使用BEGIN/END不是好主意。 – sygops

+0

爲什麼它不是一個好東西理念? –

+0

假設10次或更多,然後使用BEGIN/END,具體過程非常複雜。 – sygops