2013-01-25 51 views
0

我只是在问这个问题的知识。我有SQL Server 2008 R2,并且我创建了一个存储过程,其中有五个插入语句针对不同的表逐个执行。存储过程中的多个insert语句给出错误

我没有在该存储过程中放置​​任何锁或事务代码。现在如果第三个insert语句抛出一个错误呢?剩下的两个陈述是否会被执行?

谢谢

回答

1

根据错误类型,SQL Server将中止语句或批处理。如果它中止语句,其他插入仍然会运行。如果它中止批处理,该过程将中止并且其余插入不运行。

全部细节在an excellent article by Sommarskog由Martin Smith发表评论。

下面是一个示例设置。它包含一个存储过程TestProc,它执行六个插入。第三次插入会导致外键违例,第五次插入会导致转换错误。只有第二个错误会导致存储过程停止:

use test 
GO 
set nocount on 
IF OBJECT_ID(N't2', N'U') IS NOT NULL 
    DROP TABLE t2; 
IF OBJECT_ID(N't1', N'U') IS NOT NULL 
    DROP TABLE t1; 
IF OBJECT_ID(N'TestProc', N'P') IS NOT NULL 
    DROP procedure TestProc 
GO 
CREATE TABLE t1 (a INT NOT NULL PRIMARY KEY); 
CREATE TABLE t2 (a INT NOT NULL REFERENCES t1(a)); 
GO 
create procedure TestProc 
as 
INSERT INTO t1 VALUES (1); 
INSERT INTO t1 VALUES (2); 

INSERT INTO t2 VALUES (3); -- Foreign key error (statement abort) 
INSERT INTO t2 VALUES (1); -- Still gets inserted 
INSERT INTO t2 VALUES ('a'); -- Conversion failed (batch abort) 
INSERT INTO t2 VALUES (2); -- Does *not* get inserted 
go 
exec TestProc 
go 
select * from dbo.t1 
select * from dbo.t2 

输出:

Msg 547, Level 16, State 0, Procedure TestProc, Line 6 
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__t2__a__035179CE". 
The conflict occurred in database "test", table "dbo.t1", column 'a'. 
The statement has been terminated. 
Msg 245, Level 16, State 1, Procedure TestProc, Line 8 
Conversion failed when converting the varchar value 'a' to data type int. 
a 
----------- 
1 
2 

a 
----------- 
1 
+0

+1这取决于错误的性质。有些(如违反约束)会中止该声明。其他正在批量中止。 [更多详情](http://www.sommarskog.se/error-handling-I.html#whathappens) –

+0

如果在面试中被问到了什么问题,我很困惑? :) – Dev

+1

回答“它取决于”,并举例说明如何在违反约束后继续执行,并在数字转换错误后停止执行。 – Andomar

相关问题