zoukankan      html  css  js  c++  java
  • 简单例子理解数据库事务


    简单例子理解数据库事务

    /*-- 创建表 --*/
    --创建农行账户表bank
    if exists(select * from sysobjects where name='bank')
    	drop table bank
    go
    create table bank
    (
    	customerName char(10),		--顾客姓名
    	currentMoney money			--当前余额
    )
    /*-- 添加约束:根据银行规定,账户余额不能少于1元,否则视为销户 --*/
    alter table bank
    add constraint CK_currentMoney check(currentMoney>=1)
    /*-- 插入测试数据:张三开户,开户金额为800,李四开户,开户金额1 --*/
    insert into bank(customerName,currentMoney) values('张三',1000)
    insert into bank(customerName,currentMoney) values('李四',1)
    --查看结果
    select * from bank
    go
    
    /*-- 转账测试:张三希望通过转账,直接汇钱给李四1000元 --*/
    set nocount on --不显示受影响的行数信息
    print '查看转账事务前的余额'
    select * from bank
    go
    /*-- 开始事务 --*/
    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
    
    print '查看转账事务后的余额'
    select * from bank
    go


  • 相关阅读:
    codeforces 814B An express train to reveries
    codeforces 814A An abandoned sentiment from past
    codeforces 785D D. Anton and School
    codeforces 785C Anton and Fairy Tale
    codeforces 791C Bear and Different Names
    AOP详解
    Spring集成JUnit测试
    Spring整合web开发
    IOC装配Bean(注解方式)
    IOC装配Bean(XML方式)
  • 原文地址:https://www.cnblogs.com/keanuyaoo/p/3306451.html
Copyright © 2011-2022 走看看