如何在多个存储过程上使用事务?
您能否在一个存储过程中启动一项事务,然后在嵌套过程中回滚或提交它?
Can you start a transaction in one stored procedure and then roll it back or commit it in a nested procedure?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
提交和回滚有不同的效果
发生这种情况是因为 SQL Server 并不真正支持嵌套事务。
如果您在嵌套存储过程(而不是事务)中提交或回滚,那么您将生成错误 266,因为启动和条目上的 @@TRANCOUNT 不匹配
回滚问题可以通过使用 SET XACT_ABORT ON 来解决,这是“自动回滚” (简单地)并抑制错误 266。
提交问题......你不能这样。但是,您可以通过在存储过程条目上注明 @@TRANCOUNT 并仅在零时提交来控制发生的位置。
为了正确处理交易,请参阅我的回答:
包含 TRY CATCH ROLLBACK 模式的嵌套存储过程? 和 在 T-SQL 的 catch 块中回滚事务之前,我是否需要对事务进行计数?
Commit and rollback have different effects
This happens because SQL Server does not really support nested transactions.
If you commit or rollback in a nested stored proc (not transaction), then you'll generate error 266 because of a @@TRANCOUNT mismatch on start and entry
The rollback issue can be resolved by using SET XACT_ABORT ON which is "auto rollback" (simply) and suppresses error 266.
The commit issue... you can't as such. However, you can control where it happens by noting @@TRANCOUNT on stored proc entry and committing only if zero.
For correct transaction handling, see my answers here please:
Nested stored procedures containing TRY CATCH ROLLBACK pattern? and Have I to count transactions before rollback one in catch block in T-SQL?
您不能在嵌套过程中提交它,但启动事务会将所有嵌套过程包装在其中。因此事务对于嵌套在事务内的所有存储过程都有好处。在分布式事务中,数据完整性甚至跨越机器边界。
http://msdn.microsoft.com/en-我们/库/ms188929(v=SQL.90).aspx
You can't commit it in a nested procedure, but starting a transaction will wrap all nested procedures within it. So the transaction is good for all stored procedures nested within the transaction. In distributed transactions, data integrity even crosses machine boundaries.
http://msdn.microsoft.com/en-us/library/ms188929(v=SQL.90).aspx
您应该在同一个 SPROC 中将 BEGIN TRAN 和 COMMIT 配对。
如果您随后调用另一个也有事务的 SPROC,则后续的 BEGIN TRAN / COMMIT TRAN 对将分别递增和递减 @@Trancount。
事务在“最后”COMMIT TRAN 上提交(@@Trancount = 1)
,但是任何 ROLLBACK 都将始终回滚事务。
MSDN 有很好的解释。
You should pair up your BEGIN TRAN and COMMITs in the same SPROC
If you then call another SPROC which also has a transaction, subsequent BEGIN TRAN / COMMIT TRAN pairs will increment and decrement @@Trancount respectively.
The transaction is committed on the 'last' COMMIT TRAN (@@Trancount = 1)
However, any ROLLBACK will always roll back the transaction.
MSDN has a good explanation.
是的,这是可能的。使用 C# 等编程语言,当您使用命令传递连接和事务对象时。如果发现任何错误,则回滚事务:
Yes, it is possible. With programming languages like C#, when you pass the connection and transaction object with the command. if anything is caught as wrong than rollback the transaction: