Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a trigger ON COMMIT in Oracle?

Tags:

Is there any way in oracle database to define trigger which will be fired synchronously before COMMIT (and ROLLBACK if it throws exception) in case when specified table is changed?

like image 397
Volodymyr Frolov Avatar asked Nov 04 '10 16:11

Volodymyr Frolov


People also ask

Can I use commit in trigger in Oracle?

You can't commit inside a trigger anyway. Show activity on this post. Trigger should not commit and cannot commit. Committing in a trigger usually raises an exception unless it happens into autonomous transaction.

Can you commit inside a trigger in Oracle * 1 point?

You cannot commit inside a trigger. You can use autonomous transaction incase you want to commit and that is not recommended.


2 Answers

There is no ON COMMIT trigger mechanism in Oracle. There are workarounds however:

  1. You could use a materialized view with ON COMMIT REFRESH and add triggers to this MV. This would allow you to trigger the logic when a base table has been modified at the time of commit. If the trigger raises an error, the transaction will be rolled back (you will lose all uncommited changes).

  2. You can use DBMS_JOB to defer an action to after the commit. This would be an asynchronous action and may be desirable in some cases (for example when you want to send an email after the transaction has been successful). If you roll back the primary transaction, the job will be cancelled. The job and the primary session are independent: if the job fails the main transaction will not be rolled back.

In your case, you could probably use option (1). I personnaly don't like to code business logic in triggers since it adds a lot of complexity but technically I think it would be doable.

like image 105
Vincent Malgrat Avatar answered Sep 19 '22 17:09

Vincent Malgrat


I had a similiar problem, but option 1 was unfortunately not convenient for my case.

Another possible solution, which is also suggested by "Ask Tom", is to specify a stored procedure and simply call that procedure before executing the COMMIT. This solution is only convenient if you have access to the code which executes the COMMIT, but for my case this was the easiest solution.

like image 24
David Gausmann Avatar answered Sep 20 '22 17:09

David Gausmann