Let's say I have a SQL script that looks something like this:
BEGIN TRAN
BEGIN TRY
DISABLE TRIGGER dbo.myTrigger ON dbo.myTable;
--do something that requires the trigger to be disabled, but which might throw an error
ENABLE TRIGGER dbo.myTrigger ON dbo.myTable;
COMMIT;
END TRY
BEGIN CATCH
ROLLBACK;
THROW;
END CATCH
If an error gets thrown in the "do something" part, there are two possible things that could happen:
- Because the
ENABLE TRIGGER
statement is never hit,myTrigger
remains disabled. - The
ROLLBACK
statement in theCATCH
block rolls back everything that was attempted in the transaction, including theDISABLE TRIGGER
statement, meaningmyTrigger
remains enabled.
I would intuitively expect 2) to be true, but a colleague of mine suspects that 1) is true instead, and you would have to manually re-enable the trigger inside the CATCH
block. Neither of us could find anything on Stack Overflow or elsewhere about which interpretation is correct. So here's the question: does SQL's ROLLBACK
statement roll back the enabling or disabling of triggers?
1条答案
按热度按时间jljoyd4f1#
Having tested this myself, it seems that
ROLLBACK
does indeed undo the enabling and disabling of triggers. If I run the following script:Then run the following query:
I get back "0", meaning that the
DISABLE TRIGGER
statement was rolled back.