是一种机制,一个操作序列,包含一组数据库操作命令,并且把这个命令作为一个整体向系统提交或撤销操作请求,--要么都执行,要么就都不执行。
事务作为单个逻辑工作单元执行党的一系列操作。一个逻辑工作单元必须有4个属性:
1.原子性 :一个完整的操作,各个元素不可分割(原子的);
2.一致性 :当事务完成时,数据必须保持一致;
3.隔离性 :对数据进行修改的所有并发事务是彼此隔离;
4.持久性 :不管系统是否发生了故障,处理的结果都是永久的。
事务的分类:
1. 显示事务:通过用begin transaction明确指出事务的开始
2. 隐式事务:通过设置set implicit_transactions on 语句,将隐式事务模式设置为打开,在提交或回滚的时候自动启动新事务,不需要再描述。
3. 自动提交事务: 是SQLServer的默认模式,它将每条单独的T-Sql语句视为一个事务,。。。
eg:
use MyTransation go --创建农行账户表bank if exists(select * from sysobjects where name = 'bank') drop table bank go create table bank( customerName char(10), --顾客姓名 currentMoney money --当前余额 ) go /*---添加约束:根据银行规定,账户余额不能少于1元,否则视为注销户---*/ alter table bank add constraint CK_currentMoney CHECK(currentMoney >=1) go /*--插入测试数据,悟空开户,开户金额为1000;悟净开户,开户金额为1--*/ insert into bank(customerName,currentMoney) values('悟空',1000) insert into bank(customerName,currentMoney) values('八戒',1) --查看结果 select * from bank go --转账测试:悟空希望通过转账给八戒圣诞节红包-- --update bank set currentMoney = currentMoney-1000 -- where customerName = '悟空' --update bank set currentMoney = currentMoney+1000 -- where customerName = '八戒' --go select * from bank --用事物来封装这一组数据库操作-- 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 go print'查看转账事务后的余额' select * from bank go