When trying to insert data into tables, it could fail for various reasons like unique key violated or foreign key violated.
I could use DUP_VAL_ON_INDEX exception to know unique key is violated but how do I know which key if there are multiple columns with unique marked? Should I use triggers in this case?
(I'm using exceptions to drive the flow of stored procedures instead of querying tables to make sure data being inserted is okay.)
Exceptions (from constraints) or triggers? I say neither.
I would strongly recommend using application code and queries to drive the logic of your application, as opposed to triggers and constraints. Separating the logic from the error condition handling will only make the behaviour of your code appear more magical.
Although constraints are extremely useful as backup plan (in the case of application logic errors or changes), you are correct in that they do not assist with runtime error handling in the way that you want (i.e. do not help you expose the duplicate keys that the
INSERTstatement attempted to use).As you have no doubt determined, you could very easily use a trigger to do what you describe, but ultimately all that means is that you're simply hiding the same logical test ("does this record already exist?") in a trigger as opposed to in the application code where your
INSERTstatement will exist. If multiple triggers exist on the table, you may also be going through the overhead of executing them needlessly, as if one will raise an error, any others which ran first would have been fruitless.If you don't want to write additional statements to pre-check the condition of your data before running new
INSERTstatements, then I would suggest using something like this:At least then you will not violate the key, but you'll know if a row already existed by testing whether
SQL%ROWCOUNTis 0 (no row inserted, so must already exist) or 1.However, this still does not give you the key-violating values. You will have to write queries to find out which will violate the constraint.