博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SQL:事务(1)
阅读量:7168 次
发布时间:2019-06-29

本文共 2012 字,大约阅读时间需要 6 分钟。

摘自:

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 元到李四帐户上。
 
1   2 use stuDB 3 go 4 --创建帐户表bank-- 5 if exists(select* from sysobjects where name='bank') 6     drop table bank 7 create table bank 8 ( 9     customerName char(10),    --顾客姓名10     currentMoney money        --当前余额11 )12 go13 /*--添加约束,帐户不能少于元--*/14 alter table bank add15         constraint CK_currentMoney check(currentMoney>=1)16 /*--插入测试数据--*/17 insert into bank(customerName,currentMoney)18 select '张三',1000 union19 select '李四',120 21 select * from bank22 go23 24 /*--使用事务--*/25 use stuDB26 go27 --恢复原来的数据28 --update bank set currentMoney=currentMoney-1000 where customerName='李'29 set nocount on    --不显示受影响的行数30 print '查看转帐事务前的余额'31 select * from bank32 go33 34 /*--开始事务--*/35 begin transaction36 declare @errorSum int    --定义变量,用于累计事务执行过程中的错误37 /*--转帐--*/38 update bank set currentMoney=currentMoney-800 where customerName='张三'39 set @errorSum=@errorSum+@@error    --累计是否有错误40 update bank set currentMoney=currentMoney+800 where customerName='李四'41 set @errorSum=@errorSum+@@error --累计是否有错误42 43 print '查看转帐事务过程中的余额'44 select * from bank45 46 /*--根据是否有错误,确定事务是提交还是回滚--*/47 if @errorSum>048     begin49         print '交易失败,回滚事务.'50         rollback transaction51     end52 else53     begin54         print '交易成功,提交事务,写入硬盘,永久保存!'55         commit transaction56     end57 go58 59 print '查看转帐后的余额'60 select * from bank61 go

 

 

 

转载地址:http://vbqwm.baihongyu.com/

你可能感兴趣的文章