Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I throw an error if a parameter is null or 0?

Tags:

sql-server

I have this stored procedure:

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

How can I throw an error if the @UserId parameter is a null or zero ?

Here's what I tried but it gives a syntax error:

IF (@UserId = 0 OR @UserId IS NULL)
    THROW 70001, "UserId: Cannot be zero or null" , 1
like image 891
Alan2 Avatar asked Sep 03 '25 04:09

Alan2


2 Answers

I think you've missed the ; -colon

IF (@UserId = 0 OR @UserId IS NULL)
        THROW 70001, 'UserId: Cannot be zero or null' , 1;
like image 180
Sankar Avatar answered Sep 05 '25 01:09

Sankar


You can use 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.
like image 31
Giorgos Betsos Avatar answered Sep 05 '25 01:09

Giorgos Betsos