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 2022-03-21 15:20  hushzhang  阅读(1878)  评论(0编辑  收藏  举报

导航