簡單例子理解數據庫事務
?
/*-- 創建表 --*/ --創建農行賬戶表bank if exists(select * from sysobjects where name='bank') drop table bank go create table bank ( customerName char(10), --顧客姓名 currentMoney money --當前余額 ) /*-- 添加約束:根據銀行規定,賬戶余額不能少于1元,否則視為銷戶 --*/ alter table bank add constraint CK_currentMoney check(currentMoney>=1) /*-- 插入測試數據:張三開戶,開戶金額為800,李四開戶,開戶金額1 --*/ insert into bank(customerName,currentMoney) values('張三',1000) insert into bank(customerName,currentMoney) values('李四',1) --查看結果 select * from bank go /*-- 轉賬測試:張三希望通過轉賬,直接匯錢給李四1000元 --*/ set nocount on --不顯示受影響的行數信息 print '查看轉賬事務前的余額' select * from bank go /*-- 開始事務 --*/ begin transaction /*-- 定義變量,用于累計事務執行的過程中的錯誤 --*/ declare @errorSum int set @errorSum=0 --初始化為0,即無錯誤 /*-- 轉賬 --*/ update bank set currentMoney=currentMoney-1000 where customerName='張三' set @errorSum=@errorSum+@@error --累計是否有錯誤 update bank set currentMoney=currentMoney+1000 where customerName='李四' set @errorSum=@errorSum+@@error --累計是否有錯誤 print '查看轉賬事務過程中的余額' select * from bank /*-- 根據是否有錯誤,確定事務是提交還是撤銷 --*/ if @errorSum<>0 --如果有錯誤 begin print '交易失敗,回滾事務' rollback transaction end else begin print '交易成功,提交事務,寫入硬盤,永久保存' commit transaction end print '查看轉賬事務后的余額' select * from bank go
?
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
