(Oracle SQL) Catching a unique constraint error

心已入冬 提交于 2019-12-25 01:55:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!