[转]SQL Server 事务处理 回滚事务
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[t1]
(
[Id] [INT] NOT NULL,
[c1] [NVARCHAR](50) NULL,
[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 = ON) ON [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
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[t1]
(
[Id] [INT] NOT NULL,
[c1] [NVARCHAR](50) NULL,
[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 = ON) ON [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