T-SQL Throw Exception

To solve your problem,

Incorrect statement near 'THROW'. Expecting CONVERSATION, DIALOG, DISTRIBUTED, or TRANSACTION

put semi-colon before your throw statement:

BEGIN
    ;THROW 99001, 'O associated with the given Q Id already exists', 1;
END

And about the

"Incorrect statement near 'THROW'".

Try to use this in case you're using a older version than SQL 2012:

RAISERROR('O associated with the given Q Id already exists',16,1);

Because THROW is a new feature of SQL 2012.


This continues to occur in SQL Server 2014.

I have found that putting the semi-colon at the end of BEGIN helps.

This approach has the error

IF 'A'='A'
BEGIN
   THROW 51000, 'ERROR', 1;
END;

And this approach does not have the error

IF 'A'='A'
BEGIN;
  THROW 51000, 'ERROR', 1;
END;

For SQL Server 2012 or later:

;THROW 60000, 'your message here', 1

If you wish to pass a variable to your message use this:

DECLARE
    @Errors INT = 2,
    @ErrMsg NVARCHAR(500)

SET @ErrMsg = 'You have '+CAST(@Errors AS NVARCHAR) + ' errors!'
;THROW 60000, @ErrMsg, 1

Note that THROW blocks further code execution unlike RAISERROR.

THROW documentation

Legacy option:

RAISERROR('your message here', 16, 1)

If you wish to pass a variable to your message use this:

DECLARE
    @Errors INT = 2,
    @ErrMsg NVARCHAR(500)

SET @ErrMsg = 'You have '+CAST(@Errors AS NVARCHAR) + ' errors!'
RAISERROR(@ErrMsg, 16, 1)

To check sql server version: SELECT @@VERSION