黑马视频-事务

多个语句同时执行,一旦其中一个没有成功,就会回滚 
  1. --A账户向B账户转账
  2. alter table bank add constraint check (balance>=10) --添加约束
  3. insert into bank('001',1000)
  4. insert into bank('002',10)
  5. //============================================================================
  6. update bank set balance=balance-1000 where cid='001'
  7. update bank set balance=balance+1000 where cid='002'
  8. //由于存在大于等于10的约束,第一句执行失败,数据没有发生变化,第二句执行成功(1010)//
  9. --1.打开事物
  10. begin tran
  11. declare @sum int=0
  12. update bank set balance=balance-1000 where cid='001'
  13. set @sum=@sum+@@error
  14. update bank set balance=balance+1000 where cid='002'
  15. set @sum=@sum+@@error
  16. if @sum<>0
  17. begin
  18. rollback
  19. print '回滚'
  20. end
  21. else
  22. begin
  23. commit tran
  24. print '提交'
  25. end
  1. begin tran
  2. begin try
  3. decalre @sum int=0
  4. update bank set balance=balance-900 where cid='001'
  5. set @sum=@sum+@@error
  6. update bank set balance=balance+900 where cid='002'
  7. set @sum=@sum+@@error
  8. end try
  9. begin catch
  10. rollback
  11. end catch
  12. end 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









原文地址:https://www.cnblogs.com/wupd2014/p/4970243.html