gpt4 book ai didi

sql-server - 是否需要回滚事务?

转载 作者:行者123 更新时间:2023-12-02 11:58:06 25 4
gpt4 key购买 nike

USE AdventureWorks;
GO
BEGIN TRANSACTION;
GO
DELETE FROM HumanResources.JobCandidate WHERE JobCandidateID = 10;
DELETE FROM HumanResources.JobCandidate WHERE JobCandidateID = 11;
DELETE FROM HumanResources.JobCandidate WHERE JobCandidateID = 12;
GO
COMMIT TRANSACTION;
GO

如果第一个删除语句失败会发生什么?第二条和第三条删除语句会被执行吗?该示例没有任何错误处理,在发生异常时它会保留打开的事务,还是 SQL Server 会自动回滚该事务?开放交易=锁定资源,对吧?

我正在决定是否必须将 TRY...CATCH 应用于使用事务的存储过程。

我知道设置 xact_abort on,但想知道如果没有它会发生什么。

这是我在文档中找到的内容 - 控制事务(数据库引擎):

If an error prevents the successful completion of a transaction, SQL Server automatically rolls back the transaction and frees all resources held by the transaction

但是我在其他帖子中读到自动回滚不会被触发。

最佳答案

在您的示例中,如果不使用SET XACT_ABORT ON,即使第一个语句失败,事务也会继续并提交。在您引用的文本中,关键字是如果错误**阻止**事务的成功完成,并且DELETE语句失败不会阻止事务完成。

一个可能导致自动回滚的错误示例是,如果与数据库的连接在事务中间被切断。再往下MSDN article您引用说:

If a run-time statement error (such as a constraint violation) occurs in a batch, the default behavior in the Database Engine is to roll back only the statement that generated the error. You can change this behavior using the SET XACT_ABORT statement. After SET XACT_ABORT ON is executed, any run-time statement error causes an automatic rollback of the current transaction. Compile errors, such as syntax errors, are not affected by SET XACT_ABORT.

使用错误处理来捕获错误并在需要时回滚始终是一个好主意。

关于sql-server - 是否需要回滚事务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11414522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com