简体   繁体   中英

EXCEPTION from stored procedure is not handling correctly.

The SP EXCEPTION is not deleting the data that it should?

PROCEDURE TEST (TEST   IN  TABLE1.COLUMN1%TYPE, TEST2 IN  TABLE2.COLUMN1%TYPE)
IS
SEQ1 NUMBER;
SEQ2 NUMBER;

BEGIN
    SELECT seq_id.NEXTVAL INTO SEQ1 FROM DUAL;     
    INSERT INTO TABLE1 VALUES(SEQ1, TEST);

    SELECT seq_id2.NEXTVAL INTO SEQ2 FROM DUAL;
    INSERT INTO TABLE2 VALUES(SEQ2, TEST2);        
    COMMIT;
EXCEPTION WHEN OTHERS THEN
    ROLLBACK;
    DELETE FROM TABLE1 WHERE COLUMN0 = SEQ1;
    DELETE FROM TABLE2 WHERE COLUMN0 = SEQ1;
    RAISE;
END;

If an EXCEPTION occurrs, I want to delete everything from those tables that contains that certain ID. This SP is called X times, and I have 3 tables that have relation with a column. The first two calls are OK, if the third gives an error I want to delete those previous inserts too.

TABLES
CALL TO SP  COLUMN1 - COLUMN2 - COLUMN3
1           1         2         3
2           1         2         3
3           1         2         ERROR

EXCEPTION
Delete from TABLES WHERE COLUMN2 = 2; 

It appears that if you change your exception handler to include

DELETE FROM TABLE1 WHERE COLUMN2 = TEST2;
DELETE FROM TABLE2 WHERE COLUMN2 = TEST2;

it'll do what you're looking for.

A better solution, though, might be to remove the COMMIT and ROLLBACK from the procedure, and only commit once you know that all your work is done and successful. Best of luck.

The ROLLBACK will already undo your changes, can you explain why you want the additional delete statements?

This will work if your requirements is to rollback the inserts in case anything (=OTHERS) goes wrong. Keep in mind that your sequence will get reset as well!

PROCEDURE TEST (TEST   IN  TABLE1.COLUMN1%TYPE, TEST2 IN  TABLE2.COLUMN1%TYPE)
IS

BEGIN
  INSERT INTO TABLE1 VALUES(seq_id.NEXTVAL, TEST);
  INSERT INTO TABLE2 VALUES(seq_id2.NEXTVAL, TEST2);        
  COMMIT;
EXCEPTION WHEN OTHERS THEN
  ROLLBACK;
  RAISE;
END;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM