Is there a way to abort a stored procedure in SQL Server if a delete statement cannot be successfully executed due to a foreign key constraint violation? By default, the procedure seems to ignore the error and go on to the next statement.
For other types of error (e.g. deleting from a table that does not exist) however, the procedure aborts.
Example procedure:
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[TestSP]
AS
BEGIN
SET NOCOUNT ON;
print 'BEFORE';
DELETE FROM ExistingWithConstraints;
print 'AFTER DELETE ExistingWithConstraints';
DELETE FROM NonExisting;
print 'AFTER DELETE NonExisting';
END
produces output (note that the last message above is not printed):
BEFORE
<snip constraint violation error message>
AFTER DELETE ExistingWithConstraints
<snip invalid object name error message>