Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 ORDER OF MERGE ACTIONS

Author  Topic 

Transact Charlie
Master Smack Fu Yak Hacker

3451 Posts

Posted - 2012-01-25 : 07:52:31
This shouldn't be important to anyone..... but it may be interesting.

When you use a MERGE..

Stupid example:

; WITH mods (
[TicketableID]
, [YearMonth]
, [DaysOfWeek]
)
AS (
SELECT @TicketableID, 2222, 34
UNION SELECT @TicketableID, 2223, 33
)
MERGE routes.tbTicketableYEarMonth AS t
USING mods AS s ON
s.[TicketableID] = t.[TicketableID]
AND s.[YearMonth] = t.[YearMonth]
WHEN MATCHED THEN UPDATE SET
[DaysOfWeek] = s.[DaysOfWeek]
WHEN NOT MATCHED THEN INSERT (
[TicketableID]
, [YearMonth]
, [DaysOfWeek]
, [DaysOfMonth]
, [StartDate]
, [EndDate]
)
VALUES (
s.[TicketableID]
, s.[YearMonth]
, s.[DaysOfWeek]
, 0x142850A140
, '22230101'
, '22230106'
);


It seems that the NOT MATCHED actions are performed first, then the MATCHED actions.

I am writing some audit triggers for table which have merge statements applied to them. I'm logging each fire of the trigger in it's own batch and I'm seeing that that the NOT MATCHED inserts all happen before the matched updates.

BOL states that
quote:

For every insert, update, or delete action specified in the MERGE statement, SQL Server fires any corresponding AFTER triggers defined on the target table, but does not guarantee on which action to fire triggers first or last. Triggers defined for the same action honor the order you specify. For more information about setting trigger firing order, see Specifying First and Last Triggers.


Does anyone know if the Matched / Not Matched actions are in a deterministic order?

Of course, it doesn't matter which order (or at least it shouldn't).

Charlie
===============================================================
Msg 3903, Level 16, State 1, Line 1736
The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION

RickD
Slow But Sure Yak Herding Master

3608 Posts

Posted - 2012-01-25 : 09:16:11
Interesting, didn't realise this either, but then maybe it depends on what the engine thinks is most efficient.

Using merge, but only on tables that do not have triggers currently, will have to have a look on some that do have triggers.
Go to Top of Page
   

- Advertisement -