views:

30

answers:

3

In Microsoft SQL Server :

I've added an insert trigger my table ACCOUNTS that does an insert into table BLAH based upon the inserted values. The inserts come from only one place, and those happen one at a time. (By that, I mean, that there's never two inserts in a transaction - two web users could, theoretically click submit and have their inserts done in a near-simulataneous way.)

Do I need to adapt the trigger to handle more than one row being in inserted, the special table created for triggers - or does each individual insert transaction launch the trigger separately?

+1  A: 

in your situation each insert happens in its own transaction and fires off the trigger individually, so you should be fine. if there was ever a circumstance where you had two inserts within the same transaction you would have to modify the trigger to do either a set based insert from the 'inserted' table or some kind of cursor if additional processing is necessary.

nathan gonzalez
I know what you're saying, but it's not the transaction, but the statement - you can have BEGIN TRAN, INSERT, INSERT, COMMIT TRAN and the trigger will fire twice.
Cade Roux
+3  A: 

Each insert calls the trigger. However, if a single insert adds more than one row the trigger is only called once, so your trigger has to be able to handle multiple records.

The granularity is at the INSERT statement level not at the transaction level.

So no, if you have two transactions inserting into the same table they will each call the trigger ATOMICALLY.

BOb

PilotBob
+1  A: 

If you do only one insert in a transaction, I don't see any reason for more rows to be in inserted, except if there was a possibility of recursive trigger calls.

Still, it could cause you troubles if you'd change the behavior of your application in future and you forget to change the triggers. So just to be sure, I would rather implement the trigger as if it could contain multiple rows in inserted.

František Žiačik
I know what you're saying, but it's not the transaction, but the statement - you can have BEGIN TRAN, INSERT, INSERT, COMMIT TRAN and the trigger will fire twice.
Cade Roux