Can I rollback Dynamic SQL in SQL Server / TSQL

拜拜、爱过 提交于 2019-12-04 10:26:31

Yes. The TXNs belong to the current session/connection and dynamic SQL uses the same context.

However, @@ERROR won't pick up the error most likely: the status has to be checked immediately after the offending statement. I'd use TRY/CATCH, assuming SQL Server 2005+

Edit: The TRY/CATCH should work OK.

Don't take our word for it that try catch will work, test it yourself. Since this is dynamic sql the easiest thing to do is to make the first statement correct (and of course it mneeds to bean update,insert or delete or there is no need for atransaction) and then make a deliberate syntax error in the second statment. Then test that the update insert or delete in the first statment went through.

I also want to point out that dynamic sql as rule is a poor practice. Does this really need to be dynamic?

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