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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With