我只是想知道这个问题。我有SQL Server 2008 R2,我已经创建了一个存储过程,其中我有五个插入语句,逐个执行不同的表。
我没有在该存储过程中放置任何锁或事务代码。现在如果第3个insert语句抛出错误怎么办?剩下的两个陈述是否会被执行?
由于
答案 0 :(得分:1)
根据错误类型,SQL Server将中止语句或批处理。如果它中止语句,其他插入仍将运行。如果中止批处理,则中止该过程并且不运行其余插入。
Martin Smith的评论中an excellent article by Sommarskog的详细信息。
这是一个示例设置。它包含一个存储过程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