SET XACT_ABORT ON这个语句经常与事务连用,当这个设置为ON的时候,后面的事务片段中的语句只要有一个错误,在事务提交的时候,系统自动检测到该事务中有出错的语句,并在SET XACT_ABORT ON的作用下,自动回滚整个事务中的数据操作。但是如果把SET XACT_ABORT ON与try catch连用的时候,注意应手工设置事务回滚,比如:
begin try
SET XACT_ABORT ON
begin tran --开始执行事务
--update comment 1,minus in AW
update TUserProperty set treasure=0 where userid=@AWUserId;
--update comment 2,plus in HN
update web_users set jewels=@JewelsBeforeHN+@JewelsBeforeAW where userid=@HNUserId;
commit tran
end try
begin catch
ROLLBACK TRAN
set @ReturnValue=6;
end catch
当在事务中检测到错误的时候,try中的后续语句就不会再继续执行了(经过调试发现,即使try中用的是begin tran commit tran 片段,出错后面的语句也不会继续执行,所以必须手工回滚!),就会end try并begin catch,由于上文中的事务一直由于错误而挂起,那么必须手工rollback tran
但是单独使用SET XACT_ABORT ON及begin tran 及 commit tran (即不与try catch一起用),将自动回滚事务