Oracle:回滚仅循环的崩溃迭代

时间:2013-08-26 08:59:09

标签: oracle plsql transactions

如果一次或多次迭代崩溃,我需要帮助来完成迭代回滚,如果成功,我需要提交所有其他迭代。如果崩溃,它将回滚整个事务。认为这可以通过Savepoints来完成,但我对它们并不是很熟悉。这是我尝试实现的基本示例。

    DECLARE 
      ...
    BEGIN
      FOR i IN 1 .. 10
      LOOP
        BEGIN
          -- Some DML and stored procs with DML
          INSERT INTO a .. .;
          INSERT INTO b .. .;
          INSERT INTO a .. .;
          DELETE FROM a .. .;
          UPDATE INTO c .. .;
          m_package.some_proc_with_dml;
        EXCEPTION
          WHEN OTHERS THEN
            merror   := merror + || ', ' || + sqlerrm;
            miserror := TRUE;
        END;
      END LOOP;

      COMMIT;

      IF miserror THEN
        raise_application_error(-20000, merror);
      END IF;

    END;

先谢谢。

2 个答案:

答案 0 :(得分:5)

你可以设置一个SAVEPOINT,然后回滚到那个SAVEPOINT,例如:

    DECLARE 
      ...
    BEGIN
      FOR i IN 1 .. 10
      LOOP
        BEGIN

        SAVEPOINT my_savepoint_name;

-- Some DML and stored procs with DML
          INSERT INTO a .. .;
          INSERT INTO b .. .;
          INSERT INTO a .. .;
          DELETE FROM a .. .;
          UPDATE INTO c .. .;
m_package.some_proc_with_dml;
        EXCEPTION
          WHEN OTHERS THEN
            merror   := merror + || ', ' || + sqlerrm;
            miserror := TRUE;

            ROLLBACK TO my_savepoint_name;

        END;
      END LOOP;

答案 1 :(得分:1)

另一种选择是将循环语句包含在与PRAGMA AUTONOMOUS_TRANSACTION的单独存储过程的嵌套调用中。