Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to prevent a trigger from running in a transaction?

According to several resources, such as this,

A query that is executed within the context of a trigger is automatically wrapped in a transaction. If there are any distributed queries in the trigger code, the transaction is promoted to a distributed transaction automatically.

Simple question - is there a way to prevent this behavior? I'm looking for a way to explicitly prevent code in my trigger from running in the context of a transaction.

like image 279
Jeremy Wiggins Avatar asked Oct 06 '22 14:10

Jeremy Wiggins


1 Answers

If you are trying to do something asynchronous so that the calling transaction doesn't have to wait, you may consider Service Broker, which is designed to do exactly that - go fire off some asynchronous task, and return control to the caller, regardless of transaction scope.

Another idea is to not have your trigger perform the work, but instead pop a work item onto a queue table, and have a background process running continuously to process the queue. This isn't necessarily easy to do if your work item operates on the set of data in inserted/deleted but without more context it certainly seems like a viable option.

I don't know of a way to prevent a trigger from being a part of the calling transaction - in fact that's kind of the whole point.

like image 56
Aaron Bertrand Avatar answered Oct 10 '22 02:10

Aaron Bertrand