I have just encountered a section of SQL that is behaving not as I would expect (See below for a distilled version of the SQL in question that demonstrates the problem pattern).
(This is on SQL Server 2008 R2 SP2 64bit)
The 'do some work here' part raises an error and triggers the error handling in the CATCH block. The error number is 515 (attempt to insert a null into a non-nullable column), hence RAISERROR is reporting the error, but then the loop continues, attempts the work again, throws an error, etc. in an infinite loop.
I would expect RAISERROR to cause execution to exit the loop. What is going on here?
Thanks
WHILE (@Applied <> 1)
BEGIN
BEGIN TRY
-- === Do some work here ===
-- Successfully applied
SET @Applied = 1;
END TRY
BEGIN CATCH
-- Save the error details
SELECT
@ErrorNumber = ERROR_NUMBER(),
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();
-- Test for a deadlock or uncommittable transaction
IF (@ErrorNumber = 1205 OR @ErrorNumber = 3930)
-- Sleep for 5 seconds
WAITFOR DELAY '00:00:05';
ELSE
RAISERROR(@ErrorMessage, @ErrorSeverity, @ErrorState);
END CATCH
END
Best Answer
RAISERROR
does not typically stop execution. THROW does, but that was introduced in SQL 2012.Put a
RETURN;
orRETURN -1;
after theRAISERROR
.The following is taken from the "Remarks" section of the MSDN page for RAISERROR:
Below is a simple test of the behavior. If running on a version of SQL Server prior to 2012, comment out or remove the line with
THROW
.The above test returns the following in the "Messages" tab:
And in the bottom, left corner of SSMS it will indicate "Disconnected".