当连接关闭时,未提交的事务会发生什么?

它们是否立即回滚?他们在一段时间后回滚了吗?他们是否处于未提交状态?

Are they rolled back immediately? Are they rolled back after some period of time? Are they left in an uncommitted state?

如果使用连接池并简单地重置连接,行为是否相同?

Is the behavior the same if connection pooling is used and the connections are simply reset?

推荐答案

它可以在连接池应用时保持打开状态.示例:命令超时可以留下锁和 TXN,因为客户端发送为中止".

It can stay open while connection pooling applies. Example: command timeout can leave locks and TXN because the client sends as "abort".

2 个解决方案:

  • 在客户端进行测试,字面意思是:

  • Test in the client, literally:

IF @@TRANCOUNT <>0 回滚传输

使用 SET XACT_ABORT ON 确保 TXN 被清理:问题 1 和 问题 2

Use SET XACT_ABORT ON to ensured a TXN is cleaned up: Question 1 and Question 2

我总是使用SET XACT_ABORT ON.

来自这个 SQL 团队博客:

请注意,对于连接池,简单地关闭连接而不回滚只会返回连接到游泳池和交易将保持开放,直到后来重新使用或从池中删除.这可能导致锁开始保持不必要并导致其他超时和滚动块

Note that with connection pooling, simply closing the connection without a rollback will only return the connection to the pool and the transaction will remain open until later reused or removed from the pool. This can result in locks begin held unnecessary and cause other timeouts and rolling block

来自 MSDN,事务支持"部分"(我的粗体)

From MSDN, section "Transaction Support" (my bold)

当一个连接关闭时,它是释放回池中并进入适当的细分基于它的事务上下文.所以,你可以不关闭连接产生错误,即使分布式事务还在待办的.这允许您提交或中止分布式事务稍后.

When a connection is closed, it is released back into the pool and into the appropriate subdivision based on its transaction context. Therefore, you can close the connection without generating an error, even though a distributed transaction is still pending. This allows you to commit or abort the distributed transaction at a later time.

相关文章