问题
This is my code:
Declare
violation_of_constraint EXCEPTION;
BEGIN
-- (A FEW INSERTS HERE: A, B, C)
SAVEPOINT X;
-- (ANOTHER INSERT HERE: D)
IF DUP_VAL_ON_INDEX THEN
ROLLBACK TO X;
COMMIT;
RAISE violation_of_constraint;
END IF;
EXCEPTION
WHEN violation_of_constraint THEN
DBMS_OUTPUT.PUT_LINE('Value already exists');
COMMIT;
END;
/
When I run it (from the sql command line) I get this error at line 11:
expression is of wrong type (line 11 is "IF DUP_VAL_ON_INDEX THEN")
What could it be wrong?
回答1:
You need to define a nested PL/SQL
Block, and handle exception in EXCEPTION BLOCK as WHEN DUP_VAL_ON_INDEX
...
It should NOT be IF DUP_VAL_ON_INDEX
Declare
violation_of_constraint EXCEPTION;
BEGIN
BEGIN
-- (A FEW INSERTS HERE: A, B, C)
SAVEPOINT X;
-- (ANOTHER INSERT HERE: D)
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
ROLLBACK TO X;
COMMIT;
RAISE violation_of_constraint;
END;
EXCEPTION
WHEN violation_of_constraint THEN
DBMS_OUTPUT.PUT_LINE('Value already exists');
COMMIT;
END;
/
来源:https://stackoverflow.com/questions/22175894/oracle-sql-catching-a-unique-constraint-error