ABORT ON回滚事务?

根据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在发生运行时错误时回滚整个事务并中止批处理。

这听起来很方便。 我怎么能让它做到这一点?


当严重性级别大于或等于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错误消息级别

http://msdn.microsoft.com/en-us/library/aa937483(v=sql.80).aspx


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

set xact_abort on;

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

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

end try
begin catch

end catch
链接地址: http://www.djcxy.com/p/61813.html

上一篇: ABORT ON rollback the transaction?

下一篇: Graph subtle changes after using knitr from markdown