背景

--事务--aa转账1000给bbSELECT *FROM [dbo].[bank]name cmoney---------- ---------------------aa 1000.00bb 1.00Update bank Set cmoney=cmoney-1000 where name='aa'Update bank Set cmoney=cmoney+1000 where name='bb'--Result:第一条执行失败,第二条执行成功--ERRMEG:--The UPDATE statement conflicted with the CHECK constraint "CK_bank". The conflict occurred in database "FSLab", table "dbo.bank", column 'cmoney'.--The statement has been terminated.name cmoney---------- ---------------------aa 1000.00bb 1001.00--上面这种情况要求我们需要 使用某一种方式进行处理,这种方式就叫做事务--事务:就是指这些语句要么都执行成功,要么都不执行--事务只是一种处理机制--事务是对有可能对数据进行更改的操作而言--增加删除和修改。对查询没有用。--事务的特点:CUID 1.原子性:事务不可以再分了,事务必须是原子工作单元;对于其数据修改,要么全都执行,要么全都不执行; 2.隔离性:每一个事务是独立的,不受其他事务影响; 3.一致性:事务处理前后,数据需要保持某种程度的一致性; 4.持久性:事务一旦提交,对数据的修改永久保留;--如何使用事务:将你执行的增加删除和修改命令包含再事务的开启和提交 或者开启和回滚之间。1.事务开启:Begin Transaction2.事务提交:Commit Transaction3.事务回滚:Rollback Transaction--使用事务进行转账Begin Transaction Update bank Set cmoney=cmoney-1000 where name='aa' IF(@@ERROR<>0) --说明这一句的执行出现错误 RollBack Transaction --不可能某一句出现错误就立刻就进行提交或者回滚 Update bank Set cmoney=cmoney+1000 where name='bb' IF(@@ERROR<>0) --说明这一句的执行出现错误 RollBack Transaction--Result:--The UPDATE statement conflicted with the CHECK constraint "CK_bank". The conflict occurred in database "FSLab", table "dbo.bank", column 'cmoney'.--The statement has been terminated.Declare @ErrorCode int=0 --记录执行语句有可能出现的错误号Begin Transaction Update bank Set cmoney=cmoney-1000 where name='aa' Set @ErrorCode+=@@ERROR --只是做一个错误号的累加 Update bank Set cmoney=cmoney+1000 where name='bb' Set @ErrorCode+=@@ERRORIF(@ErrorCode<>0) --有错误 Rollback TransactionElse Commit Transaction--Result:--The UPDATE statement conflicted with the CHECK constraint "CK_bank". The conflict occurred in database "FSLab", table "dbo.bank", column 'cmoney'.--The statement has been terminated.