如何将错误捕获到forall plsql中

时间:2016-04-05 15:12:45

标签: oracle plsql

我把这个例外用于避免插入某行时出现任何错误,但我不知道为什么我可以运行。

DECLARE
TYPE dataDate IS TABLE OF DATE;
l_dataDate dataDate;
BEGIN
select data1 BULK COLLECT INTO l_dataDate from USER.TABLE_DATA;
FORALL i IN l_dataDate.FIRST..l_dataDate.LAST
    BEGIN         
        INSERT INTO USER.DIMDATE SELECT
        to_number(to_char(l_dataDate(i), 'YYYYMMDDHH24MISS')),
        to_number(to_char(l_dataDate(i), 'YYYYMMDD')),
        l_dataDate(i),
        to_number(to_char(l_dataDate(i), 'DD')),
        to_char (l_dataDate(i), 'Day'),
        to_number(to_char (l_dataDate(i), 'MM')),
        to_char (l_dataDate(i), 'Month'),
        to_number(to_char(l_dataDate(i), 'YYYY')) FROM DUAL
        WHERE NOT EXISTS (SELECT 1 FROM USER.DIMDATE WHERE COD_FECHA=to_number(to_char(l_dataDate(i), 'YYYYMMDDHH24MISS'))); 
        COMMIT;
    EXCEPTION
    WHEN OTHERS THEN
        dbms_output.put_line('ERROR '||SUBSTR(SQLERRM, 1, 200));
    END;
END;
/

做这样的事情是否可行?提前谢谢。

1 个答案:

答案 0 :(得分:2)

我认为您想在save exceptions中添加bulk collect

DECLARE
  TYPE dataDate IS TABLE OF DATE;
  l_dataDate dataDate;

  dml_errors EXCEPTION;
  PRAGMA exception_init(dml_errors, -24381);
BEGIN
  select data1 
    BULK COLLECT INTO l_dataDate 
    from USER.TABLE_DATA;

BEGIN
  FORALL i IN l_dataDate.FIRST..l_dataDate.LAST SAVE EXCEPTIONS
    INSERT INTO USER.DIMDATE 
      SELECT
          to_number(to_char(l_dataDate(i), 'YYYYMMDDHH24MISS')),
          to_number(to_char(l_dataDate(i), 'YYYYMMDD')),
          l_dataDate(i),
          to_number(to_char(l_dataDate(i), 'DD')),
          to_char (l_dataDate(i), 'Day'),
          to_number(to_char (l_dataDate(i), 'MM')),
          to_char (l_dataDate(i), 'Month'),
          to_number(to_char(l_dataDate(i), 'YYYY'))  
     FROM DUAL
    WHERE NOT EXISTS (SELECT 1 
                        FROM USER.DIMDATE 
                       WHERE COD_FECHA=to_number(
                                         to_char(l_dataDate(i), 
                                                 'YYYYMMDDHH24MISS'))); 
EXCEPTION 
  WHEN dml_errors
  THEN
    FOR i IN 1..sql%bulk_exceptions.count
    LOOP
      <<do something with the exceptions>>
    END LOOP;
END;

对于类似的东西,似乎根本没有理由使用PL / SQL。如果INSERT包含需要记录的无效数据,只需编写一个table_data语句,可能会记录D​​ML错误。