關於事務回滾,有些不明白,不知道rollback tran在什么時候用。 begin tran update 表1 update 表2 commit tran 這種寫法,在更新表1或表2時出錯,事務會不會自動回滾? 如果要加上rollback tran應該加在什么地方?每執行更新表后都用if @@error<>0 rollback tran做個判斷嗎? |
--我比較習慣加xact_abort選項
SET
XACT_ABORT
ON
begin
tran
update
表1
update
表2
commit
tran
|
BEGIN
TRANSACTION
BEGIN
TRY
sql_statement
COMMIT
END
TRY
BEGIN
CATCH
ROLLBACK
TRANSACTION
END
CATCH
|
begin
tran
update
表1
if @@error<>0
begin
rollback
tran
return
end
update
表2
if @@error<>0
begin
rollback
tran
return
end
commit
tran
|
就看你的set XACT_ABORT 是on還是off了. 當 SET XACT_ABORT 為 ON 時,如果 Transact-SQL 語句產生運行時錯誤,整個事務將終止並回滾。為 OFF 時,只回滾產生錯誤的 Transact-SQL 語句,而事務將繼續進行處理。 1.set XACT_ABORT off set XACT_ABORT off begin tran update 表1 update 表2 commit tran 結論:如果第二個語句發生錯誤,那么整個事務將會忽略而提交。因此會造成你的數據的不一致的現象。因此這種情況需要對錯誤進行判斷,如:if @@error <>0 rollback tran 2.set XACT_ABORT on set XACT_ABORT on begin tran update 表1 update 表2 commit tran 結論:如果第二個語句發生錯誤,,那么整個事務將會自動的回滾。因此可以保證你的數據的一致性,因此不需要對錯誤進行判斷。 |
上面寫錯了 declare @flag int set @flag=0 begin tran update 表1 if @@error <>0 begin set @flag=1 goto exe0 end update 表2 if @@error <>0 begin set @flag=1 goto exe0 end exe0: if @flag=0 Begin commit tran End Else Begin rollback End |