T-SQL Throw Exception

北战南征 提交于 2019-11-30 07:50:40

Try with this:

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

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;

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 error can also occur if you incorrectly code this:

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

I stared at that for four hours, putting semicolons all over the place, before I realized I'd misspelled "RAISERROR"

user1945580

put ; before THROW keyword and it will work.

As pointed out through many answers, the THROW statement was introduced in SQL Server 2012. So if you are using this version of SQL Server or later, it is recommended to use THROW, else use RAISERROR.

Also, the statement before the THROW statement must be followed by the semicolon (;) statement terminator. That's why you must include a semicolon before the throw.

Look at this article about the Differences Between RAISERROR and THROW in Sql Server

I would also like to encourage you to read the documentation from MSDN THROW (Transact-SQL) which explains these matters at the Remarks section.

I use:

CREATE PROCEDURE dbo.THROW_EXCEPTION @Message VARCHAR(MAX), @Code VARCHAR(MAX) = -1 AS BEGIN
    DECLARE @BR VARCHAR(MAX) = CHAR(13) + CHAR(10)
    DECLARE @TAB VARCHAR(MAX) = '   '
    DECLARE @T TABLE (X BIT)
    INSERT INTO @T (X) VALUES (
          @BR + @TAB + 'Error! ' + ISNULL(@Message, '{NULL}')
        + @BR + @TAB + 'Code: ' + ISNULL(@Code, '{NULL}')
        + @BR)
END

Next:

EXEC THROW_EXCEPTION 'Your Message'
-- OR
EXEC THROW_EXCEPTION 'Your Message', 'Error Code'
-- OR
EXEC THROW_EXCEPTION 'Your Message', 123456
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!