Paul Maddox

Software development team leader specialising in Microsoft Visual C# and C++ from the Northwest of England. Experience working in a globalised business and team; understanding of enterprise business operation and practices; experience reporting to executive management Skills in numerous languages and technologies; knowledge of formal software development lifecycle; experience of architecture design

Friday, May 15, 2009

What happens if a statement fails in a SQL Server stored procedure?

Answer: it carries on regardless! In other words: if you want a stored proc to specifically stop upon error, test for it and return.

Take this example:

CREATE TABLE [dbo].[PaulTest](
[Number] [int] NOT NULL
) ON [PRIMARY]

CREATE PROCEDURE uspPaulTest AS
BEGIN
INSERT INTO PaulTest (Number) VALUES (NULL) -- fails as NULL is invalid
INSERT INTO PaulTest (Number) VALUES(1) -- still gets processed as the query doesn't return
END

-- Let's test it:

SELECT * FROM PaulTest

EXEC uspPaulTest

SELECT * FROM PaulTest

-- Output:

Number
-----------
(0 row(s) affected)

Msg 515, Level 16, State 2, Procedure uspPaulTest, Line 10
Cannot insert the value NULL into column 'Number', table 'Test.dbo.PaulTest'; column does not allow nulls. INSERT fails.
The statement has been terminated.(1 row(s) affected)

Number
-----------
1
(1 row(s) affected)

0 Comments:

Post a Comment

<< Home