T-SQL 事務2
阿新 • • 發佈:2018-12-02
啟用事務完成轉賬儲存過程
1 use StudentManager 2 go 3 if exists(select * from sysobjects where name='usp_TransferAccounts') 4 drop procedure usp_TransferAccounts 5 go 6 create procedure usp_TransferAccounts 7 @inputAccount int,--轉入賬戶 8 @outputAccount int,--轉出賬戶 9 @transferMoney int --交易金額 10 as 11 declare@errorSum int 12 set @errorSum=0 13 begin transaction 14 begin 15 update CardAccount set CurrentMoney=CurrentMoney-@transferMoney 16 where StudentId=@outputAccount 17 set @errorSum=@errorSum+@@error 18 updateCardAccount set CurrentMoney=CurrentMoney+@transferMoney 19 where StudentId=@inputAccount 20 set @errorSum=@errorSum+@@error 21 if(@errorSum>0) 22 rollback transaction 23 else 24 commit transaction 25 end26 go 27 --測試失敗的轉賬 28 exec usp_TransferAccounts 100002,100001,1000 29 --查詢餘額 30 select Students.StudentId,StudentName,CurrentMoney from Students 31 inner join CardAccount on Students.StudentId=CardAccount.StudentId 32 --測試成功的轉賬 33 exec usp_TransferAccounts 100002,100001,800 34 --查詢餘額 35 select Students.StudentId,StudentName,CurrentMoney from Students 36 inner join CardAccount on Students.StudentId=CardAccount.StudentId