T-SQL Throw Exception

前端 未结 6 1325
孤独总比滥情好
孤独总比滥情好 2020-12-29 01:13

I am facing the famous \'Incorrect syntax\' while using a THROW statement in a T-SQL stored procedure. I have Googled it and checked the questions on StackOverf

相关标签:
6条回答
  • 2020-12-29 01:22

    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.

    0 讨论(0)
  • 2020-12-29 01:24

    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"

    0 讨论(0)
  • 2020-12-29 01:25

    Put ; before THROW keyword and it will work.

    0 讨论(0)
  • 2020-12-29 01:26

    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;
    
    0 讨论(0)
  • 2020-12-29 01:34

    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.

    0 讨论(0)
  • 2020-12-29 01:45

    Try with this:

    RAISERROR('your message here',16,1)
    
    0 讨论(0)
提交回复
热议问题