--A账户向B账户转账
alter table bank add constraint check (balance>=10) --添加约束
insert into bank('001',1000)
insert into bank('002',10)
//============================================================================
update bank set balance=balance-1000 where cid='001'
update bank set balance=balance+1000 where cid='002'
//由于存在大于等于10的约束,第一句执行失败,数据没有发生变化,第二句执行成功(1010)//
--1.打开事物
begin tran
declare @sum int=0
update bank set balance=balance-1000 where cid='001'
set @sum=@sum+@@error
update bank set balance=balance+1000 where cid='002'
set @sum=@sum+@@error
if @sum<>0
begin
rollback
print '回滚'
end
else
begin
commit tran
print '提交'
end
begin tran
begin try
decalre @sum int=0
update bank set balance=balance-900 where cid='001'
set @sum=@sum+@@error
update bank set balance=balance+900 where cid='002'
set @sum=@sum+@@error
end try
begin catch
rollback
end catch
end tran
@error是上一句SQL执行返回的错误信息,
1.显示事务;
2.自动提交事务:默认情况下
3.隐式事务:set IMPLICIT_TRANSACTIONS |ON|OFF| ,链接一直占用,其他链接不能使用,只有事务提交才可以使用
set IMPLICIT_TRANSACTIONS ON
事务起名: begin tran tran1 ... end tran
事务:一致性 原子性 隔离 永久性
语法步骤
1、开始事务 BEGIN TRANSACTION
2、事务提交 COMMIT TRANSACTION
3、事务回滚 ROLLBACK TRANSACTION
判断某条语句是出错
全局变量 @@ERROR
@@ERROR只能判断当前一条T-SQL语句执行是否有错,为了判断事务中所有T-SQL语句是否有错,我们需要进行累计:
set @errorSum=@errorSum+@@ERROR