鉴于此表
CREATE TABLE [dbo].[Table_2](
[X] [int] IDENTITY(1,1) NOT NULL,
[Y] [varchar](30) NULL,
CONSTRAINT [PK_Table_2] PRIMARY KEY CLUSTERED
(
[X] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
当我针对empt表运行以下代码时,第一个插入成功,但第二个插入将失败,因为代码试图为标识列插入重复值。
BEGIN
SET IDENTITY_INSERT Table_2 ON
PRINT 'Insert 1'
INSERT INTO Table_2
(X, Y)
VALUES (3, CAST(getdate() AS varchar(30)) )
PRINT 'Insert 2'
INSERT INTO Table_2
(X, Y)
VALUES (3, CAST(getdate() AS varchar(30)) )
PRINT 'Insert 3'
INSERT INTO Table_2
(X, Y)
VALUES (4, CAST(getdate() AS varchar(30)) )
SET IDENTITY_INSERT Table_2 OFF
END
输出:
Insert 1
(1 row(s) affected)
Insert 2
Ms 2627,Level 14,State 1,Line 13
违反PRIMARY KEY约束'PK_Table_2'。无法在对象'dbo.Table_2'中插入重复键。
Insert 3
(1 row(s) affected)
而不是在遇到错误时执行脚本顶部执行,而是继续执行下一个成功的insert语句。
我意识到我可以使用TRY CATCH块来捕获错误,但我的问题是:
我注意到错误的严重性为14.我认为严重程度级别错误会导致执行中止。你能否告诉我这是否是corerct以及导致脚本中止所需的最低严重程度?
答案 0 :(得分:2)
您可以使用SET选项停止对错误执行事务:
SET XACT_ABORT ON
http://msdn.microsoft.com/en-us/library/ms188792.aspx
但是,您需要将代码包装在事务中以获得全有或全无的行为。
SET XACT_ABORT ON
BEGIN TRAN
SET IDENTITY_INSERT Table_2 ON
PRINT 'Insert 1'
INSERT INTO Table_2
(X, Y)
VALUES (3, CAST(getdate() AS varchar(30)) )
PRINT 'Insert 2'
INSERT INTO Table_2
(X, Y)
VALUES (3, CAST(getdate() AS varchar(30)) )
PRINT 'Insert 3'
INSERT INTO Table_2
(X, Y)
VALUES (4, CAST(getdate() AS varchar(30)) )
SET IDENTITY_INSERT Table_2 OFF
COMMIT
SET XACT_ABORT OFF