2017-10-20 86 views
1

我正在使用遊標將數據插入表中,因爲如果記錄失敗,我只希望該記錄被丟棄並繼續插入其餘部分。PL/SQL-如何使用遊標的所有列插入到表中

所以我使用遊標來檢索信息。

有沒有辦法一次插入遊標的所有列,而不是一個一個選擇它們?

cursor c1 is 
select a,b,c,d,e from ab where a = 'something'; 

begin 
for var_c1 in c1 loop 
begin 

insert into ba (a,b,c,d,e) 
values (var_c1.all); 

-- instead of values (var_c1.a, var_c1.b, var_c1.c,var_c1.d, var_c1.e) 
exception when others then continue; 
end; 

end; 
+0

我會建議你做一些閱讀那肯定會幫助你解決你的問題。閱讀http://www.oracle.com/technetwork/issue-archive/2012/12-sep/o52plsql-1709862.html – XING

回答

1

出於性能,你應該把所有的記錄到一個集合,那麼你可以使用BULK INSERT... SAVE EXCEPTION象下面這樣:

DECLARE 
    TYPE t_tab IS TABLE OF ba%ROWTYPE; 

    l_tab   t_tab := t_tab(); 
    l_error_count NUMBER; 

    ex_dml_errors EXCEPTION; 
    PRAGMA EXCEPTION_INIT(ex_dml_errors, -24381); 
BEGIN 
    -- Fill the collection. *** 
    -- l_tab <--- ?? 
    -- *** next question is to make l_tab fill with the result of your cursor  
    -- 
    -- Perform a bulk operation. 
    BEGIN 
    FORALL i IN l_tab.first .. l_tab.last SAVE EXCEPTIONS 
     INSERT INTO ba 
     VALUES l_tab(i); 
    EXCEPTION 
    WHEN ex_dml_errors THEN 
     l_error_count := SQL%BULK_EXCEPTIONS.count; 
     DBMS_OUTPUT.put_line('Number of failures: ' || l_error_count); 
     FOR i IN 1 .. l_error_count LOOP 
     DBMS_OUTPUT.put_line('Error: ' || i || 
      ' Array Index: ' || SQL%BULK_EXCEPTIONS(i).error_index || 
      ' Message: ' || SQLERRM(-SQL%BULK_EXCEPTIONS(i).ERROR_CODE)); 
     END LOOP; 
    END; 
END; 
/

希望它可以幫助

相關問題