Blog Post

What happens in a trigger stays in the transaction: T-SQL Tuesday #106

,

Anything that happens in a trigger happens within the same transaction of the command that called it.

Part of me feels like this should be pretty obvious but it’s also one of those things that’s so obvious that it becomes easy to miss.

Let me explain:

If you run an UPDATE on a table and a trigger is fired then the UPDATE statement will not be completed until everything within that trigger finishes. If the trigger fails (throws an error) then the UPDATE statement will fail and roll back. And of course, if that UPDATE statement is part of a transaction then the transaction’s time/failure is affected by the trigger. So if you have a trigger that takes, say 1 second to run (which seems pretty quick right?) and then you have a transaction that runs 1000 commands that fire that trigger. Guess what? That transaction just had 1000 seconds added to it. Because of this, one of the many trigger best practices is to make sure that your triggers are as fast as possible.

T-SQL TuesdayNow, this post is my entry for the blog party T-SQL Tuesday. Our host this month , and the new supervisor(?) for T-SQL Tuesday, is Steve Jones (b/t). His topic is Trigger Headaches or Happiness. His invite seemed to invite a story, so here’s mine.

 

  1. We have an application that has a trigger on a table.
  2. The trigger has a cursor that loops through all of the inserts/updates.
  3. The code in the cursor runs a stored procedure for each insert/update.
  4. The stored procedure is on the other side of a linked server.
  5. The code in the stored procedure calls several local tables, and a table across a linked server .. back to the original server.

 

And then I get called because a 100 row update takes a long time. *sigh*

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating