SQL Server 2012: DENALI series-THROW statement

Hi Friends,

Continuing with my DENALI series, today I would like to talk about the new THROW statement. T-SQL TRY/CATCH were available since SQL Server 2005 but THROW and FINALLY were missing. We have THROW now, but FINALLY is yet to come 🙂

The syntax as follows:

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

A simple example could be as follows:

1_SQL_Server_2012_DENALI_series_THROW_statement

Another example of THROW, this time inside CATCH block:

USE tempdb;
GO
CREATE TABLE dbo.TestThrow
(    custID INT PRIMARY KEY
);
BEGIN TRY
    INSERT INTO dbo.TestThrow VALUES (1);
    --  Primary key violation, error number
        INSERT dbo.TestThrow(custID) VALUES(1);
        END TRY
        BEGIN CATCH
 
            PRINT 'Now in catch block.';
                THROW;
                END CATCH;

Output:

2_SQL_Server_2012_DENALI_series_THROW_statement

There are some notable differences between RIASERROR & THROW which I shall cover in another blog. I have also heard some people talking about deprecation of RAISERROR but I am not sure on this. (However, I don’t think that should be happening)

 

 

Amit Bansal

About Amit Bansal

Amit Bansal is always brainstorming around SQL Server. Despite working with SQL since 1997, he is amazed that he keeps learning new things every single day. SQL Server is AB's first love, and his wife does not mind that. He tries to share as much and spreads the SQL goodness. Internals and Performance Tuning excites him, and also gives him sleepless nights at times, simply because he is not a genius, but quite a hard worker and does not give up. It has been a long and exciting journey since 1997, you can read here: http://sqlmaestros.com/amit-bansal/ He is on Twitter: https://www.twitter.com/A_Bansal

View all posts by Amit Bansal →

One Comment on “SQL Server 2012: DENALI series-THROW statement”

Leave a Reply

Your email address will not be published. Required fields are marked *