SQL Clone
SQLServerCentral is supported by Redgate
 
Log in  ::  Register  ::  Not logged in
 
 
 

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*

SQLStudies

My name is Kenneth Fisher and I am Senior DBA for a large (multi-national) insurance company. I have been working with databases for over 20 years starting with Clarion and Foxpro. I’ve been working with SQL Server for 12 years but have only really started “studying” the subject for the last 3. I don’t have any real "specialities" but I enjoy trouble shooting and teaching. Thus far I’ve earned by MCITP Database Administrator 2008, MCTS Database Administrator 2005, and MCTS Database Developer 2008. I’m currently studying for my MCITP Database Developer 2008 and should start in on the 2012 exams next year. My blog is at www.sqlstudies.com.

Comments

Leave a comment on the original post [sqlstudies.com, opens in a new window]

Loading comments...