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

转载于:https://www.cnblogs.com/WarBlog/p/4444657.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值