SQL事務
一、事務概念
事務是一種機制、是一種操作序列,它包含了一組數據庫操作命令,這組命令要么全部執行,要么全部不執行。因此事務是一個不可分割的工作邏輯單元。在數據庫系統上執行並發操作時事務是作為最小的控制單元來使用的。這特別適用於多用戶同時操作的數據通信系統。例如:訂票、銀行、保險公司以及證券交易系統等。
二、事務屬性
事務4大屬性:
1 原子性(Atomicity):事務是一個完整的操作。
2 一致性(Consistency):當事務完成時,數據必須處於一致狀態。
3 隔離性(Isolation):對數據進行修改的所有並發事務是彼此隔離的。
4 持久性(Durability):事務完成后,它對於系統的影響是永久性的。
三、創建事務
T-SQL中管理事務的語句:
1 開始事務: begin transaction
2 提交事務:commit transaction
3 回滾事務: rollback transaction
事務分類:
1 顯式事務:用begin transaction明確指定事務的開始。
2 隱性事務:打開隱性事務:set implicit_transactions on,當以隱性事務模式操作時,SQL Servler將在提交或回滾事務后自動啟動新事務。無法描述事務的開始,只需要提交或回滾事務。
3 自動提交事務:SQL Server的默認模式,它將每條單獨的T-SQL語句視為一個事務。如果成功執行,則自動提交,否則回滾。
示例:張三轉800元到李四帳戶上。
use stuDB
go
--創建帳戶表bank--
if exists(select* from sysobjects where name='bank')
drop table bank
create table bank
(
customerName char(10), --顧客姓名
currentMoney money --當前余額
)
go
/**//*--添加約束,帳戶不能少於元--*/
alter table bank add
constraint CK_currentMoney check(currentMoney>=1)
/**//*--插入測試數據--*/
insert into bank(customerName,currentMoney)
select '張三',1000 union
select '李四',1
select * from bank
go
/**//*--使用事務--*/
use stuDB
go
--恢復原來的數據
--update bank set currentMoney=currentMoney-1000 where customerName='李'
set nocount on --不顯示受影響的行數
print '查看轉帳事務前的余額'
select * from bank
go
/**//*--開始事務--*/
begin transaction
declare @errorSum int --定義變量,用於累計事務執行過程中的錯誤
/**//*--轉帳--*/
update bank set currentMoney=currentMoney-800 where customerName='張三'
set @errorSum=@errorSum+@@error --累計是否有錯誤
update bank set currentMoney=currentMoney+800 where customerName='李四'
set @errorSum=@errorSum+@@error --累計是否有錯誤
print '查看轉帳事務過程中的余額'
select * from bank
/**//*--根據是否有錯誤,確定事務是提交還是回滾--*/
if @errorSum>0
begin
print '交易失敗,回滾事務.'
rollback transaction
end
else
begin
print '交易成功,提交事務,寫入硬盤,永久保存!'
commit transaction
end
go
print '查看轉帳后的余額'
select * from bank
go