MSSQL:触发器执行期间发生错误时会发生什么?
关于MS SQL Server的更新和插入触发器,有没有办法使它们成为原子的? 也就是说,如果触发过程中出现错误,是否可以自动回滚原来的insert或者update呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
After 触发器自动成为表上插入/更新/删除原子 DML 语句的一部分。
您只需在触发器中发出 ROLLBACK TRAN 即可回滚触发器中的所有工作和原始 I/U/D 语句。 如果有最外面的 tran,也会回滚。
重要
SQL 2000 及更早版本的触发器中的回滚会中止批处理。 有问题的 I/U/D 之后的任何代码都不会运行。 查看 Erland 精彩文章 和 另一个
对于带有 TRY/CATCH 的 SQL 2005,执行将转到 CATCH 块和批处理(也称为存储过程)等)将正常退出。
请参阅存储过程和触发器中的回滚和提交 。 触发器和 TRY/CATCH 交互位于此处
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
MSDN 中有一篇关于触发器和事务的好文章,位于:
http ://msdn.microsoft.com/en-us/magazine/cc164032.aspx
基本上,您希望使用事务来使操作原子化。
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.