zoukankan      html  css  js  c++  java
  • 存储过程中的 SET XACT_ABORT ON 和事务

    存储过程中的 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
  • 相关阅读:
    AutoCAD LISP矩形窗格绘制
    AutoCAD VBA多重延伸
    2011年3月24日星期四
    AutoCAD VBA对齐对象
    AutoCAD VBA根据对象缩放
    AutoCAD LISP绘制多个等半径圆相切
    AutoCAD LISP利用一顶点和三边长绘制三角形
    AutoCAD VBA对象的组合和拆散
    AutoCAD LISP修改已存在圆半径
    AutoCAD VBA基于对象的分层
  • 原文地址:https://www.cnblogs.com/Siny0/p/11189993.html
Copyright © 2011-2022 走看看