Rizwan Kassim
Rizwan Kassim

Reputation: 8121

Simultaneous Triggers in SQL Server

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?

Upvotes: 1

Views: 1748

Answers (3)

František Žiačik
František Žiačik

Reputation: 7614

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.

Upvotes: 1

PilotBob
PilotBob

Reputation: 3117

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

Upvotes: 3

nathan gonzalez
nathan gonzalez

Reputation: 11987

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.

Upvotes: 1

Related Questions