Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL performance with @@Error and Can they be replaced ?

I have inherited code that looks like this:

Stored Procedure UpdateSomeStuff

Update Table1 Set Col1=Para@1

IF @@Error > 0 Goto ERR

Update Table2 Set Col1=Para@2

IF @@Error > 0 Goto ERR

RETURN 0

ERR:

return  -1;

This sp is called by ADO.NET in c# like this

try
{
    myCommand.ExecuteNonQuery();
}
catch (System.Exception ex)
{
    _log.Error(ex);
    throw();
}
finally
{
    if(myConnection!=null)
    {
            myConnection.Close();
    }
}

I am just asking myself: Is the part IF @@Error > 0 Goto ERR good for anything? If an error happens the sp would return anyway and an exception would be caught in the calling method.

The calling code does not handle the return value 0 and -1. My plan would be to remove all Errorhandling in the Stored Procedure an have the same result. Am I right or is there something I missed?

like image 487
Mathias F Avatar asked Oct 27 '11 09:10

Mathias F


1 Answers

A better approach (SQL Server 2005 onwards) is to use TRY..CATCH:

BEGIN TRY
    -- Perform operations here
END TRY
BEGIN CATCH
    SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
END CATCH

A good reference is: Error Handling in SQL 2005 and Later

like image 182
Mitch Wheat Avatar answered Sep 23 '22 05:09

Mitch Wheat