事务的创建与使用

2019-07-28  本文已影响0人  承_风
事务的概念及要求
银行转账过程就是一个事务
事务的特性
事务的分类
使用SQL语句管理事务的基本步骤
--开始事务
BEGIN TRANSACTION
--提交事务
COMMIT TRANSACTION
--回滚(撤销)事务
ROLLBACK TRANSACTION

事务处理的关键问题:对事务中的insert、update、delete语句实时跟踪

判断某条语句执行是否出错的方法
use StudentManageDB
go
declare @errorSum int--定义变量,用于累计事务执行中的错误
set @errorSum=0 --初始化为,代表没有错误
begin transaction
    begin
        --转出
        update CardAccount set CurrentMoney-1000 where StudentId=100001
        set @errorSum=@errorSum+@@ERROR
        --转入
        update CardAccount set CurrentMoney+1000 where StudentId=100002
        set @errorSum=@errorSum+@@ERROR --累计是否有错误
        if(@errorSum>0)
            rollback transaction
        else
            commit transaction
    end
go
事务的应用
--编写存储过程,实现学员一卡通转账功能,要求用户输入转入和转出的金额和账户
use StudentManageDB
go
if exists(select * from Sysobjects where name='usp_TransferAccounts')
    drop procedure usp_TransferAccounts
go
create procedure usp_TransferAccounts
@inputAcount int,--转入账户
@outputAccount int, --转出账户
@transferMoney int --交易金额
as
    declare @errorSum int--定义变量,用于累计事务执行中的错误
    set @errorSum=0 --初始化为,代表没有错误
    begin transaction
    begin
        --转出
        update CardAccount set CurrentMoney-@transferMoney where StudentId=@outputAccount
        set @errorSum=@errorSum+@@ERROR
        --转入
        update CardAccount set CurrentMoney+@transferMoney where StudentId=@inputAcount
        set @errorSum=@errorSum+@@ERROR --累计是否有错误
        if(@errorSum>0)
            rollback transaction
        else
            commit transaction
    end
go
上一篇 下一篇

猜你喜欢

热点阅读