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执行是否错误来决定提交或回滚
其实,这样也行:
begin transaction
set xact_abort on
update account set balance=balance+200 where accountid='b'
update account set balance=balance-200 where accountid='a'
commit
使用set xact_abort on msdn解释: 指定当 Transact-SQL 语句出现运行时错误时,SQL Server 是否自动回滚到当前事务。
好了, 这样在出错时,自动回滚到事务开始处。在C#中可以使用try...catch 块,对工作单元中执行的SqlCommand的事务都制定
好一个,在catch中使用事务的回滚方法(C#代码部分我没试过,只是想当然)