Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server trigger execution in batch updating

I need to know about how the trigger execution happens for the below scenario.

I have 20 records in a table and I have an AFTER INSERT, UPDATE trigger on that table. When I'm updating all the records in that table using a MERGE or batch update statement, how will the trigger execute?

Does it execute for each row by row?

Or is it executing once per a batch (once for all 20 records)?

If it is execute once per batch do we need to write a loop inside the trigger to perform a task for each row?

like image 751
tarzanbappa Avatar asked Sep 01 '15 06:09

tarzanbappa


People also ask

Can we use two triggers on same table before after update?

You can create multiple triggers for the same subject table, event, and activation time. The order in which those triggers are activated is the order in which the triggers were created. Db2 records the timestamp when each CREATE TRIGGER statement executes.

Can we use update command in trigger?

AFTER UPDATE Trigger is a kind of trigger in SQL that will be automatically fired once the specified update statement is executed. It can be used for creating audit and log files which keep details of last update operations on a particular table.

Can I use CTE in trigger?

However, you can write a CTE inside a stored procedure or User Defined Functions (UDFs) or triggers or views. However, you cannot implement CTEs inside indexed views.

Do triggers run in transaction?

In all cases, a trigger is executed as part of the same transaction as the statement that triggered it, so if either the statement or the trigger causes an error, the effects of both will be rolled back.


1 Answers

Triggers in SQL Server always execute once per batch - there's no option for "for each row" triggers in SQL Server.

When you mass-update your table, the trigger will receive all the updated rows at once in the inserted and deleted pseudo tables and needs to deal with them accordingly - as a set of data - not a single row

like image 82
marc_s Avatar answered Oct 25 '22 09:10

marc_s