zoukankan      html  css  js  c++  java
  • SQL事务

    --实例:张三转800元到李四账户上

    if exists(select * from sysobjects where name='bank')
    drop table bank
    create table bank
    (
    customerName char(10), --顾客姓名
    currentMoney money --当前余额
    )

    --添加约束 ,账户不能少于1元
    alter table bank add
    constraint CK_currentMoney check(currentMoney>=1)

    --插入测试数据

    insert into bank(customerName,currentMoney)
    select 'zhangs',1000 union
    select '李四',1

    select * from bank

    /*方法一: 通过判断Error来回滚事务*/
    --开始 事务
    begin transaction --开始 事务
    declare @errorSum int =0 --定义变量,用于累计事务执行过程中的错误
    update bank set currentMoney=currentMoney-200 where customerName='zhangs'
    set @errorSum=@errorSum+@@ERROR --累计是否有错误
    update dbo.bank set currentMoney=currentMoney+200 where customerName='李四'
    set @errorSum=@errorSum+@@ERROR --累计是否有错误
    print @errorSum

    if @errorSum>0
    begin rollback transaction --事务回滚
    --print '1'
    end
    else
    begin commit transaction --提交事务
    end
    /*方法二:设置 xact_abort ON*/
    set xact_abort ON --如果不设置该项为ON,在SQL中默认为OFF,那么只回滚产生错误的Transaction-SQl语句;设为ON,回滚整个事务
    begin transaction --开始 事务
    update bank set currentMoney=currentMoney-200 where customerName='zhangs'
    update dbo.bank set currentMoney=currentMoney+200 where customerName='李四'
    commit transaction --提交事务
    select * from bank

    /*方法三:try */
    begin try
    begin transaction --开始 事务
    update bank set currentMoney=currentMoney-200 where customerName='zhangs'
    update dbo.bank set currentMoney=currentMoney+200 where customerName='李四'
    commit transaction --提交事务
    end try
    begin catch
    if @@trancount>0
    rollback
    declare @ErrMsg nvarchar(4000),@ErrSeverity int
    select @ErrMsg=ERROR_MESSAGE(),
    @ErrSeverity=ERROR_SEVERITY()

    raiserror(@ErrMsg,@ErrSeverity,1)
    end catch

    select * from bank

  • 相关阅读:
    AVR汇编初探之二《AVR的指令与汇编系统》
    Fedora 18 装完后干的事
    重建tempdb
    sqlserver 2008 r2 SqlClrProvider报错解析
    Analysis Memory In Sqlserver
    《设计模式之禅》学习笔记(七)
    容易弄错的繁体字
    《C Primer Plus》学习笔记
    什么是 Windows 能干而 Linux 干不了的事情
    MySQL中BLOB字段类型介绍
  • 原文地址:https://www.cnblogs.com/WarBlog/p/4444657.html
Copyright © 2011-2022 走看看