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


  • 相关阅读:
    ORA-06502: PL/SQL: 数字或值错误 PLS-00201: 必须声明标识符
    WINDOWS访问SAMBA提示没有权限
    C语言之isatty函数(判断文件描述词是否是为终端机)
    Centos7更改网卡名称eth0
    ReadLine自动补全分析
    GNU Readline库函数的应用示例
    GNU Readline 库及编程简介
    readline库的简单使用
    ls命令的修改时间显示到秒
    验证远程主机SSH指纹
  • 原文地址:https://www.cnblogs.com/keanuyaoo/p/3306451.html
Copyright © 2011-2022 走看看