SQL Server 事务处理 回滚事务

 创建表:

复制代码
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[t1](
    
[Id] [int] NOT NULL,
    
[c1] [nvarchar](50NULL,
    
[c2] [datetime] NULL,
 
CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED 
(
    
[Id] ASC
)
WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ONON [PRIMARY]
ON [PRIMARY]
复制代码

 

 解决方案(一)

复制代码

declare   @iErrorCount   int 
set @iErrorCount = 0
begin tran Tran_2008_10_07

insert into t1(Id, c1) values(1,'1')
set @iErrorCount=@iErrorCount+@@error

insert into t1(Id, c1) values(2,'2')
set @iErrorCount=@iErrorCount+@@error

insert into t1(Id, c1) values('xxxx3','3')
set @iErrorCount=@iErrorCount+@@error

insert into t1(Id, c1) values(4,'4')
set @iErrorCount=@iErrorCount+@@error

insert into t1(Id, c1) values(5,'5')
set @iErrorCount=@iErrorCount+@@error

if @iErrorCount=0 
  
begin   
    
COMMIT TRAN Tran_2008_10_07
  
end 
else   
  
begin   
    
ROLLBACK TRAN Tran_2008_10_07
  
end 

复制代码

 

 解决方案(二)

复制代码
begin try
    
begin tran Tran_2008_10_07

        
insert into t1(Id, c1) values(1,'1')

        
insert into t1(Id, c1) values(2,'2')

        
insert into t1(Id, c1) values('xxxx3','3')

        
insert into t1(Id, c1) values(4,'4')

        
insert into t1(Id, c1) values(5,'5')

    
COMMIT TRAN Tran_2008_10_07
end try 
begin catch 
    
raiserror 50005N'出错了' 
    
ROLLBACK TRAN Tran_2008_10_07
end catch 
复制代码

 

posted @   emanlee  阅读(12095)  评论(1编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
历史上的今天:
2007-10-07 11 Visual Studio 2005 IDE Tips and Tricks to Make You a More Productive Developer
2007-10-07 2008秋-计算机软件基础- 第四章- 顺序查找,二分查找
点击右上角即可分享
微信分享提示