8

根据Books Online 的文档SET XACT_ABORT ON,我得到的印象是,如果 T-SQL 语句引发运行时错误,则整个事务将终止并回滚:

评论

当 SET XACT_ABORT 为 ON 时,如果 Transact-SQL 语句引发运行时错误,则整个事务将终止并回滚。

在 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如果出现错误,我也认为终止批处理:

SET XACT_ABORT ON 指示 SQL Server 回滚整个事务并在发生运行时错误时中止批处理。

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

4

2 回答 2

5

SQL Server 仅在 Severity 级别大于或等于 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://docs.microsoft.com/en-us/sql/relational-databases/errors-events/database-engine-events-and-errors

于 2012-08-14T16:58:50.603 回答
1

当您使用 xact abort on 时,在try catch语句中,您可以手动引发错误以使事务回滚。

set xact_abort on;

begin try
    ...dml statements here....

if conditions here...
    raiseerror(....);

end try
begin catch

end catch
于 2012-11-14T17:16:36.080 回答