天天看點

轉賬事物操作源代碼(來自郝斌資料庫)

create database Test

use Test

create table bank

(

customerEname nvarchar(200),

currentMoney money

)

insert into bank values (‘張三’, 1000)

insert into bank values (‘李四’, 1)

alter table bank add constraint check_currentMoney check(currentMoney>=1)

update bank set currentMoney=currentMoney-1000 where customerEname=’張三’

update bank set currentMoney=currentMoney+1000 where customerEname=’李四’

begin transaction

declare @errorSum int

set @errorSum = 0

update bank set currentMoney=currentMoney-1000

where customerEname=’張三’

set @errorSum = @errorSum + @@error

update bank set currentMoney=currentMoney+1000

where customerEname=’李四’

if (@errorSum <> 0)

begin

print ‘轉賬失敗’

rollback transaction

end

else

print ‘轉賬成功’

commit transaction

end