Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL database triggers thread safe?

I have been wondering about the semantics of concurrency with regards to SQL Server database triggers. I have a database trigger that runs after an update to a table. The trigger sets a 'dateModified' column to the current time. This allows me to always know that the most recent update to the table occurred at X time. Below is what it would look like:

ALTER TRIGGER base.TR_myTrigger ON base.myTable
  AFTER INSERT, UPDATE AS
BEGIN
    DECLARE @dateModified AS DATETIMEOFFSET

    SET @dateModified = SYSDATETIMEOFFSET()
    UPDATE base.myTable
    Set dateModified =  @dateModified
    WHERE id in (SELECT DISTINCT(id) FROM inserted)
END

In my scenario, the table can be updated at any time by any number of threads. Is this trigger safe within a multi-threaded context? If thread A updates the table, and thread B reads from it immediately after, will B see a state of the table with A's updates but not trigger's updates too? Or do triggers protect the table from being read from until all actions + their triggers have been performed?

Any insight into what exactly is happening under the hood with SQL database triggers would be appreciated. Thanks!

like image 866
Ryan Avatar asked Dec 17 '14 20:12

Ryan


1 Answers

If thread A updates the table, and thread B reads from it immediately after, will B see a state of the table with A's updates but not trigger's updates too? Or do triggers protect the table from being read from until all actions + their triggers have been performed?

What this boils down to is: are the underlying operation and the trigger operation treated as an atomic unit or are they separate? The answer is: atomic. That is, you'll never see the results of the insert or update (in your case) and not see the dateModified column being dealt with via the trigger. That is, they both commit in one transaction. From the documentation:

The trigger and the statement that fires it are treated as a single transaction...

like image 120
Ben Thul Avatar answered Sep 20 '22 09:09

Ben Thul