首页 文章

从异常块继续循环

提问于
浏览
0

我知道这个问题已经得到解答,我已经提到了这个问题 . 但是,当我尝试编译以下代码,我试图通过一个包含INSERT语句的LOOP,如果insert语句不成功,我需要检查DML插入失败抛出的错误是否是UNIQUE约束或不,如果它是唯一约束错误(-1),那么我需要执行更新语句并继续循环 .

Oracle版本:11g

CREATE OR REPLACE PROCEDURE "TESTSAMPLE" AS



type array_test IS TABLE OF NUMBER;

test_arr array_test := array_test(1,   2,   3);

v_key NUMBER;
dup_chk NUMBER;
v_excp_error_code varchar2(25);


BEGIN

  FOR i IN test_arr.FIRST .. test_arr.LAST

  LOOP

    DBMS_OUTPUT.PUT_LINE(i || ' = ' || test_arr(i));
    dup_chk := test_arr(i);
    INSERT
    INTO trig_test
    VALUES('TEST324',   test_arr(i),   'Y',   'Y') returning KEY
    INTO v_key;

    IF v_key IS NOT NULL THEN
      DBMS_OUTPUT.PUT_LINE(' commiting insert ' || v_key || ' ' || dup_chk);
      COMMIT;
    END IF;

  EXCEPTION
  WHEN OTHERS THEN
    v_excp_error_code := SQLCODE;
    DBMS_OUTPUT.PUT_LINE('ERROR CODE = ' || v_excp_error_code);

    IF v_excp_error_code = '-1' THEN
      DBMS_OUTPUT.PUT_LINE('entered unique constraint exception ' || v_key);

      IF v_key = dup_chk OR v_key IS NULL THEN

        UPDATE trig_test
        SET status = 'tstsample'
        WHERE KEY = v_key;
        DBMS_OUTPUT.PUT_LINE('updated ');
        COMMIT;

      END IF;

    ELSE
      RAISE;
    END IF;
  END;  

  END LOOP;

END testsample;

上面的存储过程抛出了编译错误,

错误(33,3):PLS-00103:当遇到以下情况之一时遇到符号“EXCEPTION”:(如果循环mod为空pragma引发返回选择更新,则使用<< continue close current delete,开始情况声明结束退出goto获取锁定插入打开回滚保存点设置sql执行提交forall合并管道清除错误(56,7):PLS-00103:遇到以下其中一项时遇到符号“LOOP”:;错误(59):PLS-00103:遇到期望以下之一时符号“end-of-file”:end not pragma final instantiable order overriding static member constructor map

非常感谢您的帮助

谢谢

1 回答

  • 2

    循环后你错过了 begin . 即:

    loop
    
      begin -- ADD THIS
        dbms_output.put_line(i || ' = ' || test_arr(i));
        dup_chk := test_arr(i);
        insert into trig_test
        values
          ('TEST324', test_arr(i), 'Y', 'Y')
        returning key into v_key;
    
        if v_key is not null
        then
          dbms_output.put_line(' commiting insert ' || v_key || ' ' || dup_chk);
          commit;
        end if;
    
      exception
    

    而不是陷阱 others ,因为你只对 ORA-00001 感兴趣,你可以只捕获 when dup_val_on_index 而不检查sqlcode .

相关问题