如何使SET XACT_ABORT ON回滚事务?

时间:2012-07-23 19:36:54

标签: sql-server sql-server-2008-r2 xact-abort

基于Books Online documentation of 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 terminates the batch if there's an error

  

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

这听起来很方便。我怎么能这样做呢?

2 个答案:

答案 0 :(得分:4)

当严重级别更高或等于16时,SQL Server仅回滚事务。

参见示例:

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

答案 1 :(得分: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