I am using sql developer, and have added a constraint to one of my tables.
constraint valid_gender check(gender in ('M','F','I','T'))
When I try to add an entry with say 'x' for gender using a plsql procedure, it fails with constraint violation (as it should).
I want to add a "Catch" to the plsql procedure so that if valid_gender is voilated I can raise_application_error specific to it. Is this possible?
Constraints of the table can be retrieved from catalog-pg-constraint. using the SELECT query. Just a detail: If you don't have tables with the same name in multiple schemas, in PSQL just \d+ {TABLE_NAME} works too.
To find the name of a constraint in PostgreSQL, use the view pg_constraint in the pg_catalog schema. Join the view pg_catalog. pg_constraint with the view pg_class ( JOIN pg_class t ON t. oid = c.
A problem that indicates a syntactically correct, yet semantically illegal request. It's not meant to be used for end-user input validation, but for client developer convenience. Any constraint violation problem happening in production should be considered a bug.
Constraints are the rules enforced on data columns on table. These are used to prevent invalid data from being entered into the database. This ensures the accuracy and reliability of the data in the database. Constraints could be column level or table level.
Oracle will raise an exception that says:
ORA-02290: check constraint (yourschema.valid_gender) violated
You can catch that in an exception handler and raise your own exception instead using raise_application_error
in a couple of ways.
1) You can specifically trap the ORA-02290 exception like this:
declare
e_check_violated exception
pragma exception_init (e_check_violated, -2290);
begin
insert ...
exception
when e_check_violated then
if sqlerrm like '%(yourschema.valid_gender)%' then
raise_application_error(-20001,'Invalid gender');
else
raise;
end if;
end;
2) You can trap all exceptions and inspect them:
begin
insert ...
exception
when others then
if sqlerrm like 'ORA-02290:%(yourschema.valid_gender)%' then
raise_application_error(-20001,'Invalid gender');
else
raise;
end if;
end;
In a large application it is quite common to have an exception handling procedure to generalise this and look up the constraint-specific message in a table.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With