如何回滚存储过程中的事务?

编程入门 行业动态 更新时间:2024-10-28 08:29:53
本文介绍了如何回滚存储过程中的事务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

查看 SQL Server 联机丛书,Microsoft 似乎有一个(不正确的)在存储过程中处理嵌套事务的方法:

Looking at the SQL Server Books Online, Microsoft seems to have an (incorrect) method of handling nested transactions in a stored procedure:

显式事务可以嵌套.这主要是为了支持存储过程中的事务,这些事务既可以从已经在事务中的进程调用,也可以从没有活动事务的进程调用.

Nesting Transactions

Explicit transactions can be nested. This is primarily intended to support transactions in stored procedures that can be called either from a process already in a transaction or from processes that have no active transaction.

该示例继续显示一个存储过程,该过程启动自己的事务(无论执行它的任何进程的事务模式如何,该过程都会强制执行其事务."):

The example goes on to show a stored procedure that starts its own transaction ("The procedure enforces its transaction regardless of the transaction mode of any process that executes it."):

CREATE PROCEDURE TransProc @PriKey INT, @CharCol CHAR(3) AS BEGIN TRANSACTION InProc ... COMMIT TRANSACTION InProc;

然后可以在不运行事务的情况下调用此过程:

This procedure can then either be called without a transaction running:

EXECUTE TransProc 3,'bbb';

或使用显式交易:

BEGIN TRANSACTION OutOfProc; EXEC TransProc 1, 'aaa'; COMMIT TRANSACTION OutOfProc

他们没有解决的是存储产品时会发生什么:

What they don't address is what happens when the stored produre:

  • 因错误而失败,但事务仍在运行
  • 因错误而失败,但不会让事务继续运行
  • 遇到错误,但在事务打开的情况下继续执行
  • 遇到错误,但继续执行并回滚事务

没有:

  • SET XACT_ABORT ON
  • @@TRANCOUNT

规范示例中的任何位置.

anywhere in the canonical example.

如果我不知道更好,我会认为这行:

If i didn't know any better, i would have thought that the line:

以下示例显示了嵌套事务的预期用途.

The following example shows the intended use of nested transactions.

实际上应该阅读

以下示例展示了如何不使用嵌套事务.

The following example shows the how not to use nested transactions.

除非有人可以对这个 BOL 示例做出正面或反面?

Unless someone can make heads or tails of this BOL example?

推荐答案

您需要在事务中使用 try catch 块.因此,如果您在 catch 块中遇到错误,那么您可以回滚您的事务.

You need to use the try catch block with the transaction. So in case you get the error in your catch block then you can rollback your transaction.

请查看下面的 sql server 代码.

Please see the below sql server code for that.

BEGIN TRANSACTION; BEGIN TRY -- Some code COMMIT TRANSACTION; END TRY BEGIN CATCH ROLLBACK TRANSACTION; END CATCH;

更多推荐

如何回滚存储过程中的事务?

本文发布于:2023-10-12 20:41:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1485841.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:过程中   事务

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!