SQL SERVER 事务的使用

sql server事务的使用是为了确保数据的一致性。

通常写法

begin tran
--sql 语句1
--sql 语句2
--sql 语句3
commit tran

上面写法存在隐患,当操作(增删改)是由null引发的错误时,事务会跳过错误继续执行正常的语句。例如:

--创建表Student
create table Student(Name nvarchar(20) not null)
--建立事务
begin tran
inserted into Student(Name) values (null)
inserted into Student(Name) values ('小札')
inserted into Student(Name) values (null)
commit tran
--由null引发的错误,insert,delete,update都会跳过错误继续执行

上面结果会多一条数据为“小札”。为了避免了这样的问题:

有三种方法:其中@@error,@@trancount是全局变量,只要发生错误,@@error不等于0,只要执行一次事务,@@trancount就+1,回滚会变为0。

【方法一】:xact_abort on/off  on:开启,事务一旦出问题,全部回滚  off:关闭,不检查事务是否发生错误。

set xact_abort on
begin tran
--sql语句1
--sql语句2
--sql语句3
commit

【方法二】:每条操作语句后面判断是否回滚。

begin tran
--sql语句1
if @@error<>0
 begin
   rollback tran
   return --这里除了return跳出,也可以使用goto+标签跳出事务
 end
--sql语句2
if @@error<>0
 begin
   rollback tran
   return
 end
commit tran

【方法三】:try  catch

begin tran
 begin try
    --sql语句1
    --sql语句2
    --sql语句3
 end try
 begin catch
    if @@trancount>0
        rollback tran
 end catch
 if @@trancount>0
    commit tran
原文地址:https://www.cnblogs.com/xiaohuhu/p/14046421.html