SQL Server - semicolon before THROW

As we know, ending each statement with a semicolon is good practice. Suppose we have old code that uses RAISERROR to iterate over exceptions, and we want to exchange it for THROW .

From: THROW :

A statement before the THROW statement must be followed by a semicolon (;).

Using only ROLLBACK :

 BEGIN TRY -- some code SELECT 1; END TRY BEGIN CATCH -- some code ROLLBACK THROW; END CATCH 

and we get Incorrect syntax near 'THROW'. which works great.

But using ROLLBACK TRANSACTION works without a semicolon:

 BEGIN TRY -- some code SELECT 1; END TRY BEGIN CATCH -- some code ROLLBACK TRANSACTION THROW; END CATCH 

LiveDemo

Finally, using ROLLBACK TRANSACTION @variable :

 DECLARE @TransactionName NVARCHAR(32) = 'MyTransactionName'; BEGIN TRY -- some code SELECT 1; END TRY BEGIN CATCH -- some code ROLLBACK TRANSACTION @TransactionName THROW; END CATCH 

and get Incorrect syntax near 'THROW'. again Incorrect syntax near 'THROW'. .

Is there any special reason why the second example works (backward compatiblity / ...)?

+5
source share
1 answer

If you change the code so that it actually throws an error.

 BEGIN TRY -- some code SELECT 1/0; END TRY BEGIN CATCH -- some code ROLLBACK TRANSACTION THROW; END CATCH 

You see

Msg 3903, Level 16, State 1, Line 7 The ROLLBACK TRANSACTION request does not have a corresponding BEGIN TRANSACTION.

He is trying to return to a savepoint called THROW .

This is a valid syntax, but in the above example it does not execute at run time because the transaction does not exist. If you are in an open transaction but do not have such a savepoint (as shown below)

 BEGIN TRY BEGIN TRAN SELECT 1/0; END TRY BEGIN CATCH ROLLBACK TRANSACTION THROW; END CATCH ROLLBACK 

instead, you see the following.

Unable to drop THROW. No transaction or savepoint for this name was found.

This ambiguity seems to be the reason that there is a requirement for the preceding half-column before THROW .

+3
source

Source: https://habr.com/ru/post/1259743/


All Articles