SqlTransaction 和嵌套事务

发布于 2024-11-18 20:26:35 字数 56 浏览 4 评论 0原文

是否可以使用 SqlTransaction 类创建嵌套事务?如果是这样,我需要注意哪些规则/限制?

Is it possible to create nested transactions with a the SqlTransaction class? If so, what are the rules/limitations that I need to be aware of?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

維他命╮ 2024-11-25 20:26:35

不幸的是,SQL Server 忽略内部事务的提交,如这篇 MSDN 文章中所示。

您可以嵌套事务,但请注意该行为可能不是您所期望的。

在最外层事务提交之前不会提交任何内容。

因此,在下面...

transaction A
Query A

transaction B
Query B

Commit B
Rollback A

查询 B 的结果实际上并未提交到数据库。

Unfortunately SQL Server ignores commits on the inner transactions, as in this MSDN article.

You can nest transactions, but be aware the behavior may not be what you expect.

Nothing is committed until the outermost transaction commits.

So, in the following...

transaction A
Query A

transaction B
Query B

Commit B
Rollback A

The result of Query B is not actually committed to the database.

初相遇 2024-11-25 20:26:35

您可以在 SqlTransaction 类上使用 Save(string savePointName) 方法。这将创建一个保存点,您可以在事务内回滚到该保存点。因此,如果部分代码失败,您将回滚到之前的保存点并重新开始。

示例:

SqlTransaction tran = _transaction as SqlTransaction;
tran.Save(savePointName);

当你失败时,你会这样做:

tran.Rollback(savePointName);

你可以按照自己的意愿多次这样做。这将解决您的嵌套事务问题。

You can use Save(string savePointName) method on the SqlTransaction class. This will create a save point to which you can rollback inside the transaction. So if part of your code fails, you will rollback to the previous save point and start over.

Example:

SqlTransaction tran = _transaction as SqlTransaction;
tran.Save(savePointName);

and when you fail you will do:

tran.Rollback(savePointName);

You can do this as many times you want. That will solve your problem of nested transactions.

如果没有你 2024-11-25 20:26:35

是的,可以创建嵌套事务。

例如:

transaction A
do action #1
transaction B
do action #2
transaction C
do action #3

rollback transaction B
transaction D
do action #4
commit transaction D
transaction E
do action #5

commit transaction A

在这个序列中,只有动作 1、4 和 5 会实际发生。据我所知,除了事务本身的限制之外,嵌套事务没有任何限制。唯一必须理解的是,在提交“顶级”(嵌套的顶部)事务之前,实际上没有提交任何内容。

Yes it's possible to create nested transactions.

For instance:

transaction A
do action #1
transaction B
do action #2
transaction C
do action #3

rollback transaction B
transaction D
do action #4
commit transaction D
transaction E
do action #5

commit transaction A

with this sequence, only actions 1, 4, and 5 will have actually happened. Nested transactions have no limitations other than the limitations of a transaction by itself that I'm aware of. The only thing that must be understood is that nothing is actually committed until the "top level" (the top of the nest) transaction is committed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文