0

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

我没有在该存储过程中放置​​任何锁或事务代码。现在如果第三个插入语句抛出错误怎么办?剩下的两条语句会被执行吗?

谢谢

4

1 回答 1

1

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

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
于 2013-01-25T12:10:26.290 回答