Forum Discussion

xnadeem's avatar
xnadeem
Copper Contributor
Aug 22, 2023

SQL Server - How to get the previous error against SQL Exception

I have an issue where when I execute a stored procedure I get following error on executing the following statement

ALTER TABLE [Contact_Summary_Details] WITH NOCHECK ADD CONSTRAINT [PK_Contact_SD] PRIMARY KEY CLUSTERED (Contact_Unique_Ref) ON [PRIMARY]

Error Code:1750, Error State: 1 Error Severity:16, Line :1, ErrorMessage: Could not create constraint or index. See previous errors.

 

The SQL Statement when run throw Management studio runs fine how ever running through Stored procedure throws this exception in Try Catch

 

Is there a way to find out what was the Previous error? As Exception handling only provides the last error where as in this case there have been another error happening just before the above one

 

Cheers

 

 

  • LainRobertson's avatar
    LainRobertson
    Silver Contributor

    xnadeem 

     

    If the error is occurring in the TRY section of a TRY...CATCH block, then so long as the CATCH section is not re-throwing the error, then it will remain invisible to you outside of the CATCH block.

     

    You can test the relationship between TRY...CATCH and THROW yourself with this basic T-SQL:

     

    BEGIN TRY
    	SELECT 1/0;
    END TRY
    BEGIN CATCH
    	-- Un-comment the follow THROW to bubble the exception caught in this CATCH block back out to the caller.
    	-- While it's commented out, nothing related to the exception will be returned to the caller.
    	-- THROW;
    END CATCH

     

    Cheers,

    Lain

Resources