简体   繁体   中英

Can the INSERTED table contain values from two simultaneous transactions that fired the same trigger? SQL Server 2012

I have the same application on different hosts bulk inserting into the same table. Each bulk insert fires a trigger. The structure of the table is as follows:

Hostname    Quantity
---------------------
BOX_1       10
BOX_1       15
BOX_1       20
BOX_1       11

If I have the following code as part of the trigger:

DECLARE @hostname VARCHAR(20)
SELECT @hostname = Hostname
FROM INSERTED

Each bulk insert contains only one hostname since the application is only capturing data from the box its running on, but if two machines bulk insert simultaneously into the same table, could the INSERTED table be a combination of bulk inserts from different machines?

Or will the triggers execute sequentially, meaning the INSERTED table will always contain data from only one application at a time?

I need to know if my code setting the @hostname variable has any possibility of not being confined to just one choice.

The INSERTED (and DELETED ) table will only ever contain rows from the statement that caused the trigger to fire.

See here: https://msdn.microsoft.com/en-us/library/ms191300(v=sql.110).aspx

The inserted table stores copies of the affected rows during INSERT and UPDATE statements. During an insert or update transaction, new rows are added to both the inserted table and the trigger table. The rows in the inserted table are copies of the new rows in the trigger table.

The rows in these tables are effectively scoped to the insert/update/delete statement that caused the trigger to fire initially.

See also here for some more info: SQL Server Trigger Isolation / Scope Documentation

But bear in mind in your trigger design that some other insert or update operation (a manual bulk insert, or data maintenance) might cause your trigger to fire, and the assumption about the hostname may no longer hold. Probably this will be years down the line after you've moved on or forgotten about this trigger!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM