sql - 如果成功提交嵌套事务,父事务是否有可能失败

标签 sql sql-server tsql transactions nested-transactions

我正在尝试了解 SQL Server 中的嵌套事务。让我们考虑以下 SQL 命令链:

BEGIN TRANSACTION; -- #1
BEGIN TRANSACTION; -- #2
UPDATE foo SET column = 'something'; -- Change something in one table.
COMMIT TRANSACTION; -- #2

如果事务#2 的提交成功,事务#1 的提交是否有可能失败?如果是,您能否提供一个可能发生的示例?

最佳答案

来自 A SQL Server DBA myth a day: (26/30) nested transactions are real :

The commit of a nested transaction has absolutely no effect – as the only transaction that really exists as far as SQL Server is concerned is the outer one. ...

The rollback of a nested transaction rolls back the entire set of transactions – as there is no such thing as a nested transaction.

SELECT @@TRANCOUNT;
BEGIN TRANSACTION; -- #1
SELECT @@TRANCOUNT;
BEGIN TRANSACTION; -- #2
SELECT @@TRANCOUNT;
UPDATE foo SET [column] = 'something';
COMMIT TRANSACTION; -- #2
SELECT @@TRANCOUNT;
ROLLBACK;      -- simulate error or explicit rollback
               -- update is lost

DBFiddle Demo

如果您想要类似 Oracle 自治事务的东西,请阅读:Commit transaction outside the current transaction (like autonomous transaction in Oracle)

关于sql - 如果成功提交嵌套事务,父事务是否有可能失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51224400/

相关文章:

sql-server - ADsDSOObject和.NET为objectSID返回不同的值(类型)

sql - 即使成功更新后,T-SQL 过程、标量变量也会出错

sql - GROUP BY 和 ORDER BY 日期为月

c# - 如何使用 linq 对结果集进行分组?

mysql - mysql 中的预定事件

sql - 作为 PostgreSQL 参数的表名 - 使用 %I 的语法错误

sql - 在行不存在或条件匹配的地方加入...?

sql - MySQL 查询和文本搜索

java - 将字符串映射到枚举 jooq

sql - 如何使用 TSQL 检查 .txt 文件是否存在?