Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple condition in single IF statement

I want to add multiple condition in single IF statement in SQL.

I am not good in SQL & referred some example, all are showing only one condition in IF.

Here is my procedure.

CREATE PROCEDURE [dbo].[AddApplicationUser]    
(  
@TenantId BIGINT,  
@UserType TINYINT,
@UserName  NVARCHAR(100),  
@Password NVARCHAR(100)  
)  

AS    

BEGIN   

IF ((@TenantId IS NULL)  AND (@UserType=0 OR @UserType=1) )
  RAISERROR('The value for @TenantID should not be null', 15, 1) -- with log 

Is this correct syntax in SQL for multiconditions in IF?

like image 657
Billa Avatar asked Mar 15 '13 10:03

Billa


People also ask

Can IF statement have 2 conditions in Excel?

The IF function allows you to make a logical comparison between a value and what you expect by testing for a condition and returning a result if True or False. So an IF statement can have two results. The first result is if your comparison is True, the second if your comparison is False.

Can we write multiple conditions in if?

You can use the logical AND (&&) and logical OR (||) operators to specify multiple conditions in an if statement. When using logical AND (&&), all conditions have to be met for the if block to run. When using logical OR (||), at least one condition has to be met for the if block to run.

Can IF statement have 2 conditions in C?

There can also be multiple conditions like in C if x occurs then execute p, else if condition y occurs execute q, else execute r. This condition of C else-if is one of the many ways of importing multiple conditions.


1 Answers

Yes that is valid syntax but it may well not do what you want.

Execution will continue after your RAISERROR except if you add a RETURN. So you will need to add a block with BEGIN ... END to hold the two statements.

Also I'm not sure why you plumped for severity 15. That usually indicates a syntax error.

Finally I'd simplify the conditions using IN

CREATE PROCEDURE [dbo].[AddApplicationUser] (@TenantId BIGINT,
                                            @UserType TINYINT,
                                            @UserName NVARCHAR(100),
                                            @Password NVARCHAR(100))
AS
  BEGIN
      IF ( @TenantId IS NULL
           AND @UserType IN ( 0, 1 ) )
        BEGIN
            RAISERROR('The value for @TenantID should not be null',15,1);

            RETURN;
        END
  END 
like image 141
Martin Smith Avatar answered Oct 04 '22 17:10

Martin Smith