簡單例子理解資料庫事務

2021-08-27 14:42:59 字數 1578 閱讀 5027

/*-- 建立表 --*/

--建立農行賬戶表bank

if exists(select * from sysobjects where name='bank')

drop table bank

gocreate 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

endelse

begin

print '交易成功,提交事務,寫入硬碟,永久儲存'

commit transaction

endprint '檢視轉賬事務後的餘額'

簡單例子理解資料庫事務

簡單例子理解資料庫事務 簡單例子理解資料庫事務 sql 建立表 建立農行賬戶表bank if exists select from sysobjects where name bank drop table bank go create table bank customername char 10...

徹底理解資料庫事務

事務 transaction 一般是指要做的或所做的事情。在計算機術語中是指訪問並可能更新資料庫中各種資料項的乙個程式執行單元 unit 在計算機術語中,事務通常就是指資料庫事務。乙個資料庫事務通常包含對資料庫進行讀或寫的乙個操作序列。它的存在包含有以下兩個目的 1 為資料庫操作提供了乙個從失敗中恢...

理解資料庫中的事務

什麼是事務?我們知道,資料庫是乙個面向多使用者的共享機制,因此資料庫管理系統應當具備併發控制和封鎖機制,保證資料庫系統的正常執行。但是當多個使用者訪問資料庫的時候,如果每乙個使用者程式乙個乙個的序列執行,則每一時刻只有乙個使用者執行對資料庫的操作,其他使用者必須等待,這樣的話會嚴重影響資料庫資源的使...