Wednesday, 6 October 2010

Error Handling in SQL Server 2005, obtaining Error Message

One of the features that came into SQL 2005 was the use of Try..Catch blocks.
It is good to be able to elegantly deal with errors, but usually as a developer, you still want to know that an error has occurred, and what it is. In .Net there are exception objects you can analyse. SQL Server is different, but it is still possible to access information about the error condition.
This syntax can be used in stored procedures, but sadly not in functions, which don't support try..catch blocks in SQL Server 2005.


BEGIN TRY
          STATEMENT BLOCK
END TRY
BEGIN CATCH
           READ THE ERROR, IF RUNNING THE SPROC IN A QUERY WINDOW, YOU WILL BE 
           ABLE TO SEE THE ERROR IN THE MESSAGES WINDOW


SELECT ERROR_NUMBER() ERNumber,
         ERROR_SEVERITY() Error_Severity,
         ERROR_STATE() Error_State,
         ERROR_PROCEDURE() Error_Procedure,
         ERROR_LINE() Error_Line,
         ERROR_MESSAGE() Error_Message

PUT ERROR HANDLING CODE HERE




END CATCH





No comments: