Print Error Message in SQL Server: 3 Ways to Display it

There are several functions you can use to achieve this

Reading time icon 2 min. read


Readers help support Windows Report. We may get a commission if you buy through our links. Tooltip Icon

Read our disclosure page to find out how can you help Windows Report sustain the editorial team Read more

print error message in sql server

If you’re a developer, you might want to know how to print error messages in SQL Server. This is simpler than you think, and this guide is going to show you a couple of methods you can use.

How can I display an error message in SQL?

1. Use RAISERROR

  1. Open your configuration.
  2. Add the following code: RAISERROR('This is an error message', 16, 1);
    raiserror sql server
  3. Save changes.

Let’s explain all the parameters. Besides your error message, the number 16 describes the severity of an error, and in this case, 16 is used for general user errors.

The last value, 1, indicates a different area of code or state.

As you can see, this method is incredibly simple, and it was used on older SQL servers, before SQL Server 2012.

2. Use THROW

  1. Open your configuration.
  2. Add the following line: THROW 50000, 'This is an error message', 1;
    throw sql server
  3. Save changes.

This command is intended for SQL Server 2012 and newer. As for parameters, let’s go through them.

The 50000 is used for error number and for user-defined errors you need to use 50000 or higher. 1 represents state, similar to RAISERROR.

3. Use TRY CATCH

  1. Open your code.
  2. Now enter the following:
    BEGIN TRY
        -- Code that may cause an error
        SELECT 1 / 0; -- Division by zero to force an error
    END TRY
    BEGIN CATCH
        PRINT 'Error Message: ' + ERROR_MESSAGE();
    END CATCH

    error message sql
  3. Save changes.

This is how you can print error messages in catch block SQL Server, and this is the best method for debugging your code. Now whenever an error occurs, the ERROR_MESSAGE() will return the error text.

As you can see, it’s pretty simple to print an error message in SQL Server by following these steps.

Now that you know how to handle errors, you should be able to tackle issues such as 0x80040e14 SQL Server error and SQL Server error 18456 with ease.

More about the topics: error, sql server

User forum

0 messages