views:

432

answers:

2

Regarding Update and Insert triggers for MS SQL Server, is there a way to make them atomic? In other words, if an error occurs during the trigger, is it possible to automatically roll back the original insert or update?

A: 

There is a good article in MSDN that talks about triggers and transactions, located here:

http://msdn.microsoft.com/en-us/magazine/cc164032.aspx

Basically, you want to use transactions to make the operation atomic.

casperOne
+4  A: 

After triggers are automatically part of the insert/update/delete atomic DML statement on a table.

You simply issue ROLLBACK TRAN in the trigger to rollback all work in the trigger and the original I/U/D statement. The outermost tran is also rolled back if there is one.

Important

Rollback in a trigger for SQL 2000 and earlier aborts the batch. No code after the offending I/U/D will run. See Erland great article and another

For SQL 2005 with TRY/CATCH, execution will go to the CATCH block and your batch (aka stored proc etc) will exit normally.

See Rollbacks and Commits in Stored Procedures and Triggers. The trigger and TRY/CATCH interation is here

gbn
+1 for linking to Erland's articles.
Mark Brackett