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

Leave a comment

September 11, 2018 by Kenneth Fisher

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*

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 3,753 other subscribers

Follow me on Twitter

ToadWorld Pro of the Month November 2013
%d bloggers like this: