简体   繁体   中英

More than one insert statements in stored procedure one give error

I am asking this question for knowledge only. I have SQL Server 2008 R2 and I have created a stored procedure in which I have five insert statements that execute one by one for different tables.

I don't have placed any locks or transaction code in that stored procedure. Now what if the 3rd insert statement throws an error? Will the remaining two statements be executed or not?

Thanks

Based on the type of error, SQL Server will abort the statement or the batch. If it aborts the statement, the other inserts will still run. If it aborts the batch, the procedure is aborted and the remaining inserts are not run.

Full details in an excellent article by Sommarskog from a comment by Martin Smith.

Here's an example setup. It contains a stored procedure TestProc that does six inserts. The third insert causes a foreign key violation, and the fifth insert causes a conversion error. Only the second error causes the stored procedure to stop:

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

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM