如果参数为null或0,如何抛出错误?

时间:2016-03-11 06:30:52

标签: sql-server

我有这个存储过程:

CREATE PROCEDURE [dbo].[get_test_status]
    @CreatedBy      INT OUTPUT,
    @TestStatusId   INT OUTPUT,
    @UserTestId     INT,
    @UserId         INT
AS

如果@UserId参数为null或为零,如何抛出错误?

这是我尝试的但它给出了语法错误:

IF (@UserId = 0 OR @UserId IS NULL)
    THROW 70001, "UserId: Cannot be zero or null" , 1

2 个答案:

答案 0 :(得分:2)

您可以使用RAISERROR

IF @UserId = 0 OR @UserId IS NULL
  RAISERROR (N'This is message %s %d.', -- Message text.
             10, -- Severity,
             1, -- State,
             N'number', -- First argument.
             5); -- Second argument.
-- The message text returned is: This is message number 5.

答案 1 :(得分:2)

我认为你错过了; -colon

IF (@UserId = 0 OR @UserId IS NULL)
    THROW 70001, "UserId: Cannot be zero or null" , 1;

修改 你应该使用' - 单引号

IF (@UserId = 0 OR @UserId IS NULL)
        THROW 70001, 'UserId: Cannot be zero or null' , 1;