存储过程中的 SET XACT_ABORT ON 和事务
2016-08-17 22:49
316 查看
在存储过程中写SET XACT_ABORT
ON 有什么用?
SET XACT_ABORT ON是设置事务回滚的!当为ON时,如果你存储中的某个地方出了问题,整个事务中的语句都会回滚
为OFF时,只回滚错误的地方
第一种情况:每次成功执行一条语句就立刻进行提交事务 (注意commit tran的位置)
use sales --指定数据库 go alter table T_UserInfoTwo add constraint ck_id check(id between 1 and 15) --给T_UserInfoTwo表的Id添加约束 go if exists(select * from sys.objects where name='proc_userinfotwo_insert') drop proc proc_userinfotwo_insert --如果存在此存储过程则删除 go create proc proc_userinfotwo_insert --创建存储过程 as begin declare @id int set @id=1 while @id<20 begin begin try begin tran --开启事务(设置反悔点) insert into T_UserInfoTwo values(@id,'小雅',21,0,'18620005006','123@qq.com',' 湖南常德','朋友',1,'坏心眼女巫'); commit tran --提交事务(不反悔,将数据插入到表中) end try begin catch rollback tran --抛出异常后回滚 end catch set @id =@id+1; --变量自增1 end end go
第二种情况,当循环插入数据的时候,只要抛出异常,之前所有的 操作都进行回滚 (注意commit tran的位置与第一种情况是不一样的)
use sales --指定数据库 go alter table T_UserInfoTwo add constraint ck_id check(id between 1 and 15) --给T_UserInfoTwo表的Id添加约束 go if exists(select * from sys.objects where name='proc_userinfotwo_insert') drop proc proc_userinfotwo_insert --如果存在此存储过程则删除 go create proc proc_userinfotwo_insert --创建存储过程 as begin declare @id int set @id=1 begin begin try begin tran --开启事务(设置反悔点) while @id<20 begin insert into T_UserInfoTwo values(@id,'小雅',21,0,'18620005006','123@qq.com',' 湖南常德','朋友',1,'坏心眼女巫'); set @id =@id+1; --变量自增1 end commit tran --提交事务(不反悔,将数据插入到表中) 特别要注意这个commit tran的位置,不如果不想每执行完一条数据就提交事务,就应该讲这个commit tran放到while循环外面来。 end try begin catch begin rollback tran --抛出异常后回滚 end end catch end end go
相关文章推荐
- 在存储过程中SET XACT_ABORT ON 有什么用
- SET XACT_ABORT { ON | OFF }SQL Server 是否自动回滚到当前事务
- SET XACT_ABORT { ON | OFF } 设置整个事务终止并回滚方法
- SQL_SET XACT_ABORT ON(事务回滚)
- SQL存储过程中的几个常见设定SET QUOTED_IDENTIFIER/NOCOUNT/XACT_ABORT ON/OFF
- SET XACT_ABORT { ON | OFF }SQL Server 是否自动回滚到当前事务
- set xact_abort ON 你懂的, 在分布式数据库事务中,用到. 在事务中,若出现错误,系统即默认回滚事务
- SET XACT_ABORT ON [SQL SERVER] 设置事务全部回滚
- SET XACT_ABORT ON 数据库事务
- set XACT_ABORT ON与判断事务的异同
- SQL存储过程前面有语句set ANSI_NULLS ON set QUOTED_IDENTIFIER ON
- 存储过程中的 SET NOCOUNT ON
- 错误 '800a0e78' 存储过程中缺少 set nocount on 导致错误
- 事务的回滚设置(SET XACT_ABORT)
- 关于Set Nocount ON的性能 |c#调用存储过程的返回值总是-1
- SET XACT_ABORT用法(事务)
- Transaction Save Point (SET XACT_ABORT { ON | OFF })
- sql server 存储过程中 SET NOCOUNT ON是什么意思?
- ADO.NET事务和Set Xact_Abort 以及MSDTC
- SQL SERVER存储过程是否返回受影响的行,SET NOCOUNT ON|OFF