• 关于事务,存储过程,触发器的简单例子


    用一个简单的Bank表分别对事务,存储过程和触发器写个简单例子

    Bank表有连个字段:Id(账号)varchar(4);

              Balance(账号金额)money (check约束 Balance>10)

    1.事务(转账)

     1 begin transaction
     2 declare @error int;
     3 set @error=0;
     4 update bank set Balance=Balance-1000 where Id='0001';
     5 set @error=@error+@@ERROR;
     6 update bank set Balance=Balance+1000 where Id='0002';
     7 set @error=@error+@@ERROR;
     8 if @error>0
     9 begin
    10  rollback transaction
    11 end
    12 else
    13 begin
    14  commit transaction
    15 end

    使用try-catch)(减少代码量)

    begin transaction
    begin try
     update bank set Balance=Balance-1000 where Id='0001';
     update bank set Balance=Balance+1000 where Id='0002';
     commit transaction
    end try
    begin catch
     rollback transaction
    end catch

    2存储过程(转账)

    alter proc usp_MoveBalance
    @cash money,
    @inBankId char(4),
    @OutBankId char(4),
    @currentCash money output,  --显示余额
    @flag bit output            --是否转成功
    as
    begin
    begin transaction
     begin try
      update bank set Balance=Balance-@cash where Id=@OutBankId;
      update bank set Balance=Balance+@cash where Id=@InBankId;
      set @flag=1;
      commit transaction 
     end try
     begin catch
      set @flag=0;
      rollback transaction
     end catch 
     select @currentCash=Balance from bank where Id=@OutBankId;
    end
    
    --执行存储过程
    
    declare @flag bit;
    declare @currentCash money;
    exec usp_MoveBalance 100,'0002','0001',@currentCash output,@flag output
    select @flag
    select @currentCash

    3.触发器-(如果给任何账户打钱,都会把钱打到'0004'这个账号)(instead of)还有另一种触发器after(写for默认是after)

    create trigger TriBankUpdate on bank
    instead of Update
    as
    begin
     declare @afterUpdateCash money;
     declare @beforeUpdateCash money;
     declare @cash money;
     select @afterUpdateCash=Balance from inserted;
     select @beforeUpdateCash=Balance from deleted;
     set @cash=@afterUpdateCash-@beforeUpdateCash;
     if @cash>0
     begin
      Update bank set Balance=Balance+@cash where Id='0004';
     end
    end
    
    --------------------------------------
    
    --测试
    
    select * from bank
    
    update bank set Balance=Balance+1000 where Id='0001';
  • 相关阅读:
    Qt 处理相机图像实时显示引入队列,防止数据读写冲突导致卡顿、崩溃
    OpenCV -- ffmpeg 视频输入输出VideoCapture和VideoWriter的使用
    OpenCV -- 伪彩 applyColorMap
    C++中内存拷贝函数(C++ memcpy)//深拷贝 浅拷贝
    逻辑运算符&&和&的区别、| 和 || 的区别
    openCV -- namedWindow( )函数用法总结
    var a="" 与a=" ",的区别;
    创建Node.js应用
    JS数值精度函数
    js字符串截取函数slice()、sunstring()、substr()
  • 原文地址:https://www.cnblogs.com/bravo2012/p/2635648.html
Copyright © 2020-2023  润新知