Do triggers get rolled back if a transaction fails in SQL Server?

六眼飞鱼酱① 提交于 2019-12-30 03:59:09

问题


I have some triggers on some tables that perform a function when something is deleted or updated. During a transaction, if the trigger executes and later in the transaction it gets rolled back, does the trigger also get rolled back?


回答1:


Yes.

So long as the trigger fires as part of the transaction, any changes in makes within the database would also get rolled back.

Nitpick - a trigger is a trigger, it will not get rolled back. The effects of the trigger will be.




回答2:


OK, a real transaction that is rolled back at the time of the insert/update/delete would also rollback whatever actions the trigger took. However if you are taking more than one action in a transaction, the transaction processing would have to be explicit in your code for the rollback to happen to early actions.

So if I delete from table1 and the trigger fires and then the transaction fails, everything is rolledback.

If I delete from table 1 and the trigger fires and I delete from table2 as part of the same script or stored proc or dynamicSQL sent from the application then two things could happen. If you have a formal explicit transaction (that correctly handles errors), everything that happens including the trigger actions get rolled back, if you were relying on an implicit transaction (which only rollback the last action), then it would not change anything before the part that failed.



来源:https://stackoverflow.com/questions/9334597/do-triggers-get-rolled-back-if-a-transaction-fails-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!