Thursday, June 9, 2016

MS SQL Server - Exception vs RaiseError

Below is just an observation that needs further investigation.

It appears that while using ODBC to connect to MS SQL Server there's a difference between RAISERROR and an occurence of an exception.

Performing a SELECT 1/0 within a stored procedure called as Post-SQL query results in an error like:

Database driver error...
...
FnName: Execute Direct -- [Informatica][ODBC SQL Server Wire Protocol driver][Microsoft SQL Server]Divide by zero error encountered.]

Now, this is perfectly fine. An error occured, the session has failed. But what if we need to store some audit information in a log table in case of error in stored procedure? It's possible with TRY...CATCH. Whenever an error occurs, the CATCH block is executed. We can log the information and do a RAISERROR afterwards to fail the session.

But the session never fails. There's no track of RAISERROR in session log, the session completes successfully.

UPDATE:

The issue is caused with returning any dataset. Any print statement or result set seems to cover the error. Even the information about number of affected rows. Hence, the solution is to:

  • remove any SELECT / PRINT statements from within the Stored Procedure
  • suppressing the information about affected rows by using the SET NOCOUNT ON

2 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete