Internet Engineer
Internet Engineer

Reputation: 2534

Catch fails in SQL when failure is induced on purpose

Catch fails in Stored Procedure when failure is induced on purpose.

I am trying to test the catch portion in my Stored Procedure by changing a column name after I create the stored procedure. But the catch never gets executed and it fails at the line where the error is. Any ideas on what I could be doing wrong?

Steps to reproduce:

* Create Table ErrorTest 

    CREATE TABLE [dbo].[ErrorTest](

        [ErrorTest] [varchar](50) NULL

    ) ON [PRIMARY]

* Create Stored Procedure TestError

    SET NOCOUNT ON;

    DECLARE @EmailMessage AS VARCHAR(5000)

    BEGIN

        BEGIN TRY

            SELECT  ErrorTest FROM ErrorTest

        END TRY

        BEGIN CATCH             
            declare @error int, @message varchar(4000), @xstate int;
            select @error = ERROR_NUMBER()
                 , @message = ERROR_MESSAGE()
                 , @xstate = XACT_STATE();

        SET @EmailMessage = 'Failure ' + CHAR(13) + 'Error Code: '+ CAST(@error AS VARCHAR)  + CHAR(13) + @message
            EXEC    [leads].[usp_SendEmail]
                    @Mysubject = N'FAILURE!',
                    @Mybody = @EmailMessage,
                    @Myrecipients = N'[email protected]'                                     
        END CATCH
        END

Upvotes: 1

Views: 144

Answers (1)

Oleg Dok
Oleg Dok

Reputation: 21756

The SP is never executes - it simply not compiles - thus there is nothing to execute

Rewrite your TRY section in a way like this and try once more:

BEGIN TRY

    EXEC('SELECT  ErrorTest FROM ErrorTest')

END TRY

Upvotes: 5

Related Questions