Tuesday, May 9, 2017

How to Raise Custom Exception with THROW in SQL Server.

   
      There are a lot of ways to raise an exception in SQL Server, It feels like every version comes with a new one. I am going to focus on the THROW command which became available with SQL Server 2012. We used to have RAISEERROR function, Microsoft recommends THROW instead for the new applications.

THROW [ { error_number | @local_variable },
{ message | @local_variable }, { state | @local_variable } ]

error_number : Constant or variable that represents the exception. It is an integer which should be between 50000 and 2147483647
message : This is the message SQL server displays when exception occurs. It's type is nvarchar(2048)
state : It indicates the state to associate with the message. It's type is tinyint

If you are using THROW in a CATCH block, you don't need to specify any parameters unless you want to customize the error.
The statement before THROW must be ended with (;) All exceptions severity level thrown by THROW are 16

Here is a simple example.

This example shows how THROW raises the last thrown error.

No comments:

Post a Comment