Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch a unique constraint error in a PL/SQL block?

Tags:

oracle

plsql

Say I have an Oracle PL/SQL block that inserts a record into a table and need to recover from a unique constraint error, like this:

begin     insert into some_table ('some', 'values'); exception     when ...         update some_table set value = 'values' where key = 'some'; end; 

Is it possible to replace the ellipsis for something in order to catch an unique constraint error?

like image 499
Thiago Arrais Avatar asked Jan 13 '09 18:01

Thiago Arrais


People also ask

How do you handle unique constraint error?

To handle unique constraint violations: Catch uniqueness exceptions thrown by the database at the lowest level possible — in the UnitOfWork class. Convert them into Result. Use the UnitOfWork in the controller to explicitly commit pending changes and see if there are any uniqueness constraint violations.

How do you know when a unique constraint is violated?

The constraint name can be found by looking at the error message itself. In parenthesis following the ORA-00001 notice, the constraint should be listed. This process will then return the name of the table that features the violated constraint.

How do you handle unique constraints in Oracle?

begin merge into some_table st using (select 'some' name, 'values' value from dual) v on (st.name=v.name) when matched then update set st. value=v. value when not matched then insert (name, value) values (v.name, v.


1 Answers

EXCEPTION       WHEN DUP_VAL_ON_INDEX       THEN          UPDATE 
like image 171
Ricardo Villamil Avatar answered Sep 21 '22 07:09

Ricardo Villamil