SQL SERVER – Convert Old Syntax of RAISEERROR to THROW
Posted
by Pinal Dave
on SQL Authority
See other posts from SQL Authority
or by Pinal Dave
Published on Sat, 16 Aug 2014 01:30:21 +0000
Indexed on
2014/08/18
16:32 UTC
Read the original article
Hit count: 444
PostADay
|sql
|SQL Authority
|SQL Error Messages
|SQL Query
|SQL Server
|SQL Tips and Tricks
|T SQL
I have been quite a few comments on my Facebook page and here is one of the questions which instantly caught my attention.
“We have a legacy application and it has been a long time since we are using SQL Server. Recently we have upgraded to the latest version of SQL Server and we are updating our code as well.
Here is the question for you, there are plenty of places we have been using old style RAISEERROR code and now we want to convert it to use THROW. Would you please suggest a sample example for the same.”
Very interesting question. THROW was introduced in SQL Server 2012 to handle the error gracefully and return the error message. Let us see quickly two examples of SQL Server 2012 and earlier version.
Earlier Version of SQL Server
BEGIN TRY
SELECT 1/0
END TRY
BEGIN CATCH
DECLARE @ErrorMessage NVARCHAR(2000), @ErrorSeverity INT
SELECT @ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY()
RAISERROR (@ErrorMessage, @ErrorSeverity, 1)
END CATCH
SQL Server 2012 and Latest Version
BEGIN TRY
SELECT 1/0
END TRY
BEGIN CATCH
THROW
END CATCH
That’s it! We are done!
Reference: Pinal Dave (http://blog.SQLAuthority.com)
Filed under: PostADay, SQL, SQL Authority, SQL Error Messages, SQL Query, SQL Server, SQL Tips and Tricks, T SQL
© SQL Authority or respective owner