日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

SQL Server事务

發(fā)布時間:2025/4/5 数据库 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SQL Server事务 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

轉(zhuǎn)自:http://blog.csdn.net/zerolsy/article/details/2123637

一、事務概念
??? 事務是一種機制、是一種操作序列,它包含了一組數(shù)據(jù)庫操作命令,這組命令要么全部執(zhí)行,要么全部不執(zhí)行。因此事務是一個不可分割的工作邏輯單元。在數(shù)據(jù)庫系統(tǒng)上執(zhí)行并發(fā)操作時事務是作為最小的控制單元來使用的。這特別適用于多用戶同時操作的數(shù)據(jù)通信系統(tǒng)。例如:訂票、銀行、保險公司以及證券交易系統(tǒng)等。
?
二、事務屬性
事務4大屬性:
1?? 原子性(Atomicity):事務是一個完整的操作。
2?? 一致性(Consistency):當事務完成時,數(shù)據(jù)必須處于一致狀態(tài)。
3?? 隔離性(Isolation):對數(shù)據(jù)進行修改的所有并發(fā)事務是彼此隔離的。
4?? 持久性(Durability):事務完成后,它對于系統(tǒng)的影響是永久性的。
?
三、創(chuàng)建事務
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語句視為一個事務。如果成功執(zhí)行,則自動提交,否則回滾。
?
示例:張三轉(zhuǎn)800元到李四帳戶上。
? use stuDB
go
--創(chuàng)建帳戶表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)
/**//*--插入測試數(shù)據(jù)--*/
insert into bank(customerName,currentMoney)
select '張三',1000 union
select '李四',1

select * from bank
go

/**//*--使用事務--*/
use stuDB
go
--恢復原來的數(shù)據(jù)
--update bank set currentMoney=currentMoney-1000 where customerName='李'
set nocount on??? --不顯示受影響的行數(shù)
print '查看轉(zhuǎn)帳事務前的余額'
select * from bank
go

/**//*--開始事務--*/
begin transaction
declare @errorSum int??? --定義變量,用于累計事務執(zhí)行過程中的錯誤
/**//*--轉(zhuǎn)帳--*/
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 '查看轉(zhuǎn)帳事務過程中的余額'
select * from bank

/**//*--根據(jù)是否有錯誤,確定事務是提交還是回滾--*/
if @errorSum>0
??? begin
??????? print '交易失敗,回滾事務.'
??????? rollback transaction
??? end
else
??? begin
??????? print '交易成功,提交事務,寫入硬盤,永久保存!'
??????? commit transaction
??? end
go

print '查看轉(zhuǎn)帳后的余額'
select * from bank
go

總結(jié)

以上是生活随笔為你收集整理的SQL Server事务的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。