首页 > 解决方案 > Raising Errors in SQL Server ( THROW Command) with IF condition - SQL Server

问题描述

I am trying to update my script from the RAISERROR command to the THROW command. I am in an IF statement condition and if the condition is true, the throw the error. For the RAISEERROR command I do not have an issue, however when I change to the THROW command, there is no possible.

RAISERROR command:

CREATE OR ALTER PROCEDURE Auction.uspAddProductToAuction
    (@ProductID INT,
     @ExpireDate DATETIME = NULL,
     @InitialBidPrice MONEY = NULL) 
AS
    DECLARE @IND_ADD_PRODUCT TINYINT
    SET @IND_ADD_PRODUCT = 1

    IF ([Auction].[ufnGetStock](@ProductID) = 0) --> true
    BEGIN
        SET @IND_ADD_PRODUCT = 0
        RAISERROR ('The product is not in auction campaign discount or a product was not inserted', 1, 0)
    END

THROW command:

CREATE OR ALTER PROCEDURE Auction.uspAddProductToAuction
    (@ProductID INT,
     @ExpireDate DATETIME = NULL,
     @InitialBidPrice MONEY = NULL) 
AS
    DECLARE @IND_ADD_PRODUCT TINYINT
    SET @IND_ADD_PRODUCT = 1

    IF ([Auction].[ufnGetStock](@ProductID) = 0) --> true
    BEGIN
        SET @IND_ADD_PRODUCT = 0
        THROW 50001, 'The product is not in auction campaign discount or a product was not inserted', 0 
    END

I get this error:

Msg 102, Level 15, State 1, Procedure uspAddProductToAuction, Line 14 [Batch Start Line 180]
Incorrect syntax near 'THROW'

Thank you in advance

标签: sql-serverif-statementstored-procedureserror-handling

解决方案


备注 THROW 语句之前的语句必须后跟分号 (;) 语句终止符。

SET @IND_ADD_PRODUCT = 0;--<--!!
THROW 50001, 'The product is not in auction campaign discount or a product was not inserted',0;
END

推荐阅读