Does anyone know how SQL Server determines the order triggers (of same type, i.e. before triggers) are executed. And is there any way of changing this so that I can specify
Use this system stored procedure:
sp_settriggerorder[@triggername = ] 'triggername', [@order = ] 'value', [@stmttype = ] 'statement_type'
You can guarantee which trigger is fired first, which trigger is fired last and which ones fire in the middle by using sp_settriggerorder. If you need to synchronize more than three it does not appear possible in SQL Server 2005.
Here is a sample taken from here (The linked article has much more information).
sp_settriggerorder [ @triggername = ] ‘[ triggerschema. ] triggername’
, [ @order = ] ‘value’
, [ @stmttype = ] ’statement_type’
[ , [ @namespace = ] { ‘DATABASE’ | ‘SERVER’ | NULL } ]
You can use sp_settriggerorder to define the order of each trigger on a table.
However, I would argue that you'd be much better off having a single trigger that does multiple things. This is particularly so if the order is important, since that importance will not be very obvious if you have multiple triggers. Imagine someone trying to support the database months/years down the track. Of course there are likely to be cases where you need to have multiple triggers or it really is better design, but I'd start assuming you should have one and work from there.
Use This :
For example :
USE AdventureWorks;
GO
EXEC sys.sp_settriggerorder @triggername = N'', -- nvarchar(517)
@order = '', -- varchar(10)
@stmttype = '', -- varchar(50)
@namespace = '' -- varchar(10)
The First and Last triggers must be two different triggers.
First : Trigger is fired first.
Last : Trigger is fired last.
None : Trigger is fired in undefined order.
And see this link for value of @stmttype
: DDL Events
And for @namespace = { 'DATABASE' | 'SERVER' | NULL } and for more information see : DDL Triggers
A million dollar statement in this context -
sp_settriggerorder: Specifies the AFTER triggers that are fired first or last. The AFTER triggers that are fired between the first and last triggers are executed in undefined order.
Source : MSDN
If you're at the point of worrying about trigger orders then you really should take a step backwards and consider what you are trying to do and if there is there a better way of doing it. The fact that this isn't an easy thing to change should be telling you something.
Triggers always look like a really neat solution, and in the right place they are highly valuable, but the price is high, and it's really easy to create debugging nightmares with them. I've lost many hours in the past trying to debug some obscure database behavior only to find that the cause is burrowed away in an overlooked trigger.