SQL Server事务的回滚

MSDN上定义:事务是单个的工作单元。如果某一事务成功,则在该事务中进行的所有数据修改均会提交,成为数据库中的永久组成部分。如果事务遇到错误且必须取消或回滚,则所有数据修改均被清除。

  当前有张账户表Account ,字段 AccountID和Balance,Balance存在一个check( balance>=0), 数据 a,100; b,100。模拟银行转账的话,需要从a从扣除150,同时b中增加150。在sql

中实现都是通过update就行了。

update Account set balance=balance+150 where accountid='b'

update Account set balance=balance-150 where accountid='a'

但是,如果updateb时出错, a的balance会小于0 这样的话造成 a,100; b,250 。明显出错。使用事务的话如果存在错误会回滚到事务的开始

 

复制代码

declare @op1 int
, @op2 int
set @op1 = 0
Set @op2 = 0
begin transaction
update account set balance = balance + 200 where accountid = ' b '
set @op1 = @@ERROR
update account set balance = balance - 200 where accountid = ' a '
set @op2 = @@ERROR
if ( @op1 > 0 or @op2 > 0 )
rollback
else
commit
复制代码

 这样的话需要在对每个sql语句执行时写句 x= @@ERROR

 并在最后通过判断每个sql执行是否错误来决定提交或回滚

posted on   hushzhang  阅读(1907)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
历史上的今天:
2020-03-21 win10使用教程(电脑windows系统基础使用教程快速入门手册图文详解)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示