PL/SQL 错误处理后继续执行

Posted

技术标签:

【中文标题】PL/SQL 错误处理后继续执行【英文标题】:PL/SQL Continue exection after error handled 【发布时间】:2019-08-14 12:50:43 【问题描述】:

我是 PL/SQL 的新手,我遇到了以下情况。

在下面的脚本中,我希望脚本在发现任何异常时继续迭代。异常已处理,但我无法在循环外执行 continue 语句。

declare
  l_max_ID number;
  l_Temp_val number;
  type array_t is varray(135) of varchar2(30);
  arrayTable array_t := array_t('YSXQTAAA', 'YSXQTAFA', ... );
  array array_t := array_t('YSXQNAAA', 'YSXQNAFA', ...);
begin
    dbms_output.put_line(arrayTable.count);

    for i in 1..arrayTable.count loop
        dbms_output.put_line('Tabla impactada ' || arrayTable(i));
        execute immediate 'select max(id)+1 from ' || arrayTable(i) into l_max_ID;
        execute immediate 'alter sequence ' || array(i) || ' restart start with ' || TO_CHAR(l_Max_ID);
        dbms_output.put_line('alter sequence RS1.' || array(i) || ' restart start with ' || TO_CHAR(l_Max_ID));
    end loop;

  rollback;
EXCEPTION
 WHEN NO_DATA_FOUND THEN
        /* HAndle an error that gets raised when a query returns nothing */
        dbms_output.put_line('Error 1');

    WHEN TOO_MANY_ROWS THEN
        /* HAndle the situation when too much data is returned such as with a select-into */
        dbms_output.put_line('Error 2');

    WHEN OTHERS THEN
        dbms_output.put_line('Error 3');
end;

问题是某些表没有 id 列并且选择抛出异常。该数组包含一百多个元素,删除每个元素都需要很长时间。

【问题讨论】:

【参考方案1】:

将异常处理块放入循环中:

begin
    dbms_output.put_line(arrayTable.count);

    for i in 1..arrayTable.count loop
        begin
            dbms_output.put_line('Tabla impactada ' || arrayTable(i));
            execute immediate 'select max(id)+1 from ' || arrayTable(i) into l_max_ID;
            execute immediate 'alter sequence ' || array(i) || ' restart start with ' || TO_CHAR(l_Max_ID);
            dbms_output.put_line('alter sequence RS1.' || array(i) || ' restart start with ' || TO_CHAR(l_Max_ID));
        EXCEPTION
        WHEN NO_DATA_FOUND THEN
                /* HAndle an error that gets raised when a query returns nothing */
                dbms_output.put_line('Error 1');
                continue;

            WHEN TOO_MANY_ROWS THEN
                /* HAndle the situation when too much data is returned such as with a select-into */
                dbms_output.put_line('Error 2');
                continue;

            WHEN OTHERS THEN
                dbms_output.put_line('Error 3');
                continue;
        end;
    end loop;

  rollback;
end;

【讨论】:

以上是关于PL/SQL 错误处理后继续执行的主要内容,如果未能解决你的问题,请参考以下文章

引发异常后 PL/SQL 继续

PL/SQL数据开发那点事

PL/SQL Oracle 错误处理

PL/SQL 异常错误处理

pl/sql 中的错误处理

ORACLE PL/SQL编程总结