Tuesday, March 27, 2012

are after triggers really after?

The other day when I was preparing for Microsoft exam 70-229 and I was reading up on triggers and I noticed that the documentation states that the default behavoir of triggers is to fire after the update\insert\delete transaction on the table that the trigger is created on. However, I have noticed that this is not totally accurate. If you setup a trace in profiler with the with all of the xxxstarted and xxxcompleted events for the T-SQL and stored procedure event classes you will notice that the originating transaction starts, then the trigger starts, then the trigger completes and then the originating transaction completes.

So after thinking about this for a while, I have to come to the conclusion that sql server must consider the trigger as part of the orignating transaction, and must therefore complete the trigger before the originating transaction commits. With this in mind, should'nt the default behavoir of triggers be considered "during" and not "after".I believe they fire after the update\insert\delete, but before the commit. They certainly occur during the transaction, because an error in a poorly written trigger can roll back the whole thing.|||I believe they fire after the update\insert\delete, but before the commit. They certainly occur during the transaction, because an error in a poorly written trigger can roll back the whole thing.

I think both statements are accurate. What differentiates an 'after' trigger from a before (or INSTEAD OF) trigger is that it (the INSTEAD OF trigger) executes before any transaction is opened on the underlying table/view. Perhaps a blinding statement of the obvious, but as often the case in semantics, the BEFORE trigger needed an 'opposite' and that opposite became 'after'.

Regards,

hmscott

No comments:

Post a Comment