Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

SQL Server ERROR_NUMBER() Function: A How-To Guide

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

The ERROR_NUMBER() function in SQL Server returns the error number of the error that caused the CATCH block of a TRY...CATCH construct to execute. To use it, wrap your statement in BEGIN TRY...END TRY and BEGIN CATCH...END CATCH, then call ERROR_NUMBER() inside the CATCH block—typically to log the error or decide how to handle it. It returns an int and is only valid inside a CATCH block; outside one, it returns NULL.

What You'll Need

  • SQL Server 2005 or later (ERROR_NUMBER() was introduced with TRY...CATCH in SQL Server 2005).
  • A connection to a SQL Server instance with permission to create and run a test procedure or script (for example, a development database).
  • SQL Server Management Studio (SSMS) or Azure Data Studio, or any client that can execute T-SQL.
  • Basic familiarity with T-SQL batches, stored procedures, and error handling.

Step-by-Step

  1. Open a query window in SSMS or Azure Data Studio and connect to your test database. Avoid running experiments in production.
  2. Write a TRY...CATCH block. The basic pattern is:
    BEGIN TRY
        -- statement that may fail
        SELECT 1/0;
    END TRY
    BEGIN CATCH
        SELECT ERROR_NUMBER() AS ErrorNumber;
    END CATCH;
  3. Run the batch. The division-by-zero error (number 8134) is caught, and the CATCH block returns 8134. If you run SELECT ERROR_NUMBER(); on its own outside a CATCH block, it returns NULL—this is expected.
  4. Capture the other error functions alongside it. In the same CATCH block, select ERROR_MESSAGE(), ERROR_SEVERITY(), ERROR_STATE(), ERROR_PROCEDURE(), and ERROR_LINE() to get a complete picture of the failure.
  5. Log the error to a table. Create a simple logging table and insert the values from the CATCH block:
    CREATE TABLE dbo.ErrorLog (
        LogID int IDENTITY PRIMARY KEY,
        ErrorNumber int,
        ErrorMessage nvarchar(4000),
        ErrorSeverity int,
        ErrorState int,
        ErrorProcedure nvarchar(128),
        ErrorLine int,
        LogDate datetime DEFAULT GETDATE()
    );
    
    BEGIN TRY
        SELECT 1/0;
    END TRY
    BEGIN CATCH
        INSERT dbo.ErrorLog (ErrorNumber, ErrorMessage, ErrorSeverity, ErrorState, ErrorProcedure, ErrorLine)
        VALUES (ERROR_NUMBER(), ERROR_MESSAGE(), ERROR_SEVERITY(), ERROR_STATE(), ERROR_PROCEDURE(), ERROR_LINE());
        THROW; -- re-raise the error after logging
    END CATCH;
  6. Use ERROR_NUMBER() for conditional handling. You can branch on the number to take different actions, for example:
    BEGIN CATCH
        IF ERROR_NUMBER() = 2627 -- primary key violation
            PRINT 'Duplicate key';
        ELSE IF ERROR_NUMBER() = 547 -- foreign key violation
            PRINT 'Constraint violation';
        ELSE
            THROW;
    END CATCH;
  7. Test with a stored procedure. Put the TRY...CATCH inside a procedure and call it. ERROR_PROCEDURE() will return the procedure name, and ERROR_NUMBER() still returns the underlying error number.
  8. Verify the results. Query your log table to confirm the error number and message were captured. Compare the number with the official SQL Server error list (for example, 8134 is divide-by-zero, 2627 is unique constraint violation).

Common Mistakes

  • Calling ERROR_NUMBER() outside a CATCH block. It returns NULL. The function is only meaningful while handling an error inside CATCH.
  • Assuming it returns the error number for every statement. It returns the number for the error that caused the current CATCH block to run. If you nest TRY...CATCH, the innermost CATCH sees its own error.
  • Forgetting that some errors are not caught. Errors with severity 20 or higher that terminate the connection, and compile-time errors in the same batch, may not be trapped by TRY...CATCH. ERROR_NUMBER() will not help there.
  • Using ERROR_NUMBER() after the CATCH block ends. The values are only available inside the CATCH block; store them in variables if you need them later.
  • Not re-raising the error. If you swallow the error after logging, the caller may think the operation succeeded. Use THROW; (SQL Server 2012+) or RAISERROR to re-raise after logging.
  • Confusing ERROR_NUMBER() with @@ERROR. @@ERROR is set after each statement and is easily overwritten; ERROR_NUMBER() inside CATCH is more reliable for the caught error.

Tips

  • Always log ERROR_NUMBER() together with ERROR_MESSAGE(), ERROR_SEVERITY(), ERROR_STATE(), ERROR_PROCEDURE(), and ERROR_LINE() for a complete diagnostic record.
  • Use ERROR_NUMBER() in a CASE or IF to translate common error numbers into friendly messages for application users.
  • Keep a reference of common error numbers (e.g., 2627 unique constraint, 547 foreign key, 8134 divide by zero) to make branching readable.
  • In SQL Server 2012 and later, prefer THROW; over RAISERROR for re-raising because it preserves the original error number and message.
  • Test your error handling with deliberate failures (divide by zero, constraint violations) in a non-production database.

Troubleshooting

  • ERROR_NUMBER() returns NULL. You are not inside a CATCH block, or the error was not caught (e.g., compile-time error or severity 20+). Move the call inside CATCH and verify the error is catchable.
  • The CATCH block does not run. Check that the failing statement is inside the TRY block and that the error is one that TRY...CATCH handles. Some errors, such as syntax errors, abort the batch before TRY...CATCH can act.
  • Error number is not what you expected. The number reflects the actual error raised. Use ERROR_MESSAGE() to confirm. For example, a foreign key violation returns 547, not a generic number.
  • Logging fails inside CATCH. If the log insert itself errors, the original error may be masked. Wrap the logging in its own TRY...CATCH or use a reliable logging method, and ensure the log table exists and is accessible.
  • Nested TRY...CATCH confusion. If an inner CATCH handles an error and does not re-raise, the outer CATCH will not see it. Decide where you want to handle and where to re-raise.

Frequently Asked Questions

What does ERROR_NUMBER() return?

It returns the integer error number of the error that caused the CATCH block to execute. Outside a CATCH block, it returns NULL.

Can I use ERROR_NUMBER() in a SELECT statement outside TRY...CATCH?

Yes, syntactically, but it will return NULL because there is no active error context. It is only useful inside a CATCH block.

Does ERROR_NUMBER() work in Azure SQL Database?

Yes, TRY...CATCH and the ERROR_* functions are supported in Azure SQL Database and Azure SQL Managed Instance, as well as on-premises SQL Server 2005 and later.

How is ERROR_NUMBER() different from @@ERROR?

@@ERROR is set after every statement and is reset by the next statement. ERROR_NUMBER() inside CATCH reliably returns the number of the error being handled, even after other statements in the CATCH block.

Can I get the error number for errors that are not caught by TRY...CATCH?

No. Some errors, such as those with severity 20 or higher that terminate the connection, and certain compile-time errors, are not trapped by TRY...CATCH, so ERROR_NUMBER() cannot report them.

What are some common error numbers I might see?

Examples include 2627 (unique constraint violation), 547 (foreign key constraint violation), 8134 (divide by zero), and 208 (invalid object name). The exact number depends on the error raised.