MSDN上定義:事務是單個的工作單元。如果某一事務成功,則在該事務中進行的所有數據修改均會提交,成為數據庫中的永久組成部分。如果事務遇到錯誤且必須取消或回滾,則所有數據修改均被清除。
當前有張賬戶表Account ,字段 AccountID和Balance,Balance存在一個check( balance>=0), 數據 a,100; b,100。模擬銀行轉賬的話,需要從a從扣除150,同時b中增加150。在sql
中實現都是通過update就行了。
update Account set balance=balance+150 where accountid='b'
update Account set balance=balance-150 where accountid='a'
但是,如果updateb時出錯, a的balance會小於0 這樣的話造成 a,100; b,250 。明顯出錯。使用事務的話如果存在錯誤會回滾到事務的開始
declare @op1 int
, @op2 int
set @op1 = 0
Set @op2 = 0
begin transaction
update account set balance = balance + 200 where accountid = ' b '
set @op1 = @@ERROR
update account set balance = balance - 200 where accountid = ' a '
set @op2 = @@ERROR
if ( @op1 > 0 or @op2 > 0 )
rollback
else
commit
, @op2 int
set @op1 = 0
Set @op2 = 0
begin transaction
update account set balance = balance + 200 where accountid = ' b '
set @op1 = @@ERROR
update account set balance = balance - 200 where accountid = ' a '
set @op2 = @@ERROR
if ( @op1 > 0 or @op2 > 0 )
rollback
else
commit
這樣的話需要在對每個sql語句執行時寫句 x= @@ERROR
並在最后通過判斷每個sql執行是否錯誤來決定提交或回滾