黑马视频-事务
多个语句同时执行,一旦其中一个没有成功,就会回滚
--A账户向B账户转账alter table bank add constraint check (balance>=10) --添加约束insert into bank('001',1000)insert into bank('002',10)//============================================================================update bank set balance=balance-1000 where cid='001'update bank set balance=balance+1000 where cid='002'//由于存在大于等于10的约束,第一句执行失败,数据没有发生变化,第二句执行成功(1010)//--1.打开事物begin trandeclare @sum int=0update bank set balance=balance-1000 where cid='001'set @sum=@sum+@@errorupdate bank set balance=balance+1000 where cid='002'set @sum=@sum+@@errorif @sum<>0beginrollbackprint '回滚'endelsebegincommit tranprint '提交'end
begin tranbegin trydecalre @sum int=0update bank set balance=balance-900 where cid='001'set @sum=@sum+@@errorupdate bank set balance=balance+900 where cid='002'set @sum=@sum+@@errorend trybegin catchrollbackend catchend tran
@error是上一句SQL执行返回的错误信息,
1.显示事务;
2.自动提交事务:默认情况下
3.隐式事务:set IMPLICIT_TRANSACTIONS |ON|OFF| ,链接一直占用,其他链接不能使用,只有事务提交才可以使用
set IMPLICIT_TRANSACTIONS ON
事务起名: begin tran tran1 ... end tran
事务:一致性 原子性 隔离 永久性
语法步骤
1、开始事务 BEGIN TRANSACTION
2、事务提交 COMMIT TRANSACTION
3、事务回滚 ROLLBACK TRANSACTION
判断某条语句是出错
全局变量 @@ERROR
@@ERROR只能判断当前一条T-SQL语句执行是否有错,为了判断事务中所有T-SQL语句是否有错,我们需要进行累计:
set @errorSum=@errorSum+@@ERROR

浙公网安备 33010602011771号