gpt4 book ai didi

sql-server - 如何使 SET XACT_ABORT ON 回滚事务?

转载 作者:行者123 更新时间:2023-12-02 16:27:53 24 4
gpt4 key购买 nike

基于Books Online documentation of SET XACT_ABORT ON ,我的印象是,如果 T-SQL 语句引发运行时错误,则整个事务将终止并回滚:

Remarks

When SET XACT_ABORT is ON, if a Transact-SQL statement raises a run-time error, the entire transaction is terminated and rolled back.

在 SQL Server 2008 R2 中对此进行测试:

SET XACT_ABORT ON;
BEGIN TRANSACTION;
PRINT 'TranCount befor an error = '+CAST(@@Trancount AS varchar(50))

DROP TABLE QuertyAsdf

PRINT 'TranCount after an error = '+CAST(@@Trancount AS varchar(50))

给出输出:

TranCount befor an error = 1
Msg 3701, Level 11, State 5, Line 6
Cannot drop the table 'QwertyAsdf', because it does not exist or you do not have permission.
TranCount after an error = 1

我的印象是 SET XACT_ABORT ON terminates the batch if there's an error :

SET XACT_ABORT ON instructs SQL Server to rollback the entire transaction and abort the batch when a run-time error occurs.

听起来很方便。我怎样才能让它也这样做?

最佳答案

SQL Server 仅在严重级别大于或等于 16 时回滚事务。

参见示例:

Msg 544, Level 16, State 1, Line 1
Cannot insert explicit value for identity column in table 'ORC_ORCAMENTO' whenIDENTITY_INSERT is set to OFF.

在 SQL Server 2008 R2 上测试

SET XACT_ABORT ON;
BEGIN TRANSACTION;
PRINT 'TranCount befor an error = '+CAST(@@Trancount AS varchar(50))
insert into ORC_ORCAMENTO (ORCID, ORCNOME, ORCATIVO) VALUES (1, 'TESTE_ALEXP', 0);
PRINT 'TranCount after an error = '+CAST(@@Trancount AS varchar(50))

返回

TranCount befor an error = 1
Msg 544, Level 16, State 1, Line 5
Cannot insert explicit value for identity column in table 'ORC_ORCAMENTO' when IDENTITY_INSERT is set to OFF.
TranCount after an error = 0

查看 Microsoft 错误消息级别

https://learn.microsoft.com/en-us/sql/relational-databases/errors-events/database-engine-events-and-errors

关于sql-server - 如何使 SET XACT_ABORT ON 回滚事务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11619292/

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