Win
Win

Reputation: 2613

Two sql if statements

I want to run through two IF statements in sql. The IF's are two different conditions, example:

IF (@user == 'Bob')
BEGIN
   SELECT * FROM table Where id = 1
END
IF (@animal == 'Cat')
BEGIN
   SELECT * FROM table WHERE id = 50
END

What i want back are rows 1 if only the first condition is correct or 1 and 50 if both conditions are met. This fails at the second IF statement, is there another keyword I need to add?

Upvotes: 2

Views: 585

Answers (5)

Petio Ivanov
Petio Ivanov

Reputation: 305

IF (@user = 'Bob')
BEGIN
    IF (@animal = 'Cat')
    BEGIN
       SELECT * FROM table WHERE id = 50
    END
    ELSE
    BEGIN   
       SELECT * FROM table Where id = 1
    END
END

Upvotes: 1

Jared Beekman
Jared Beekman

Reputation: 320

Try this nested if function:

SELECT * FROM table Where id = IF(@user=='Bob',1,IF(@animal=='Cat',50));

Upvotes: -1

Tamim Al Manaseer
Tamim Al Manaseer

Reputation: 3724

I recommend a single statement:

SELECT
   *
FROM table
WHERE
    (@user = 'Bob' AND Id = 1)
    OR
    (@animal= 'Cat' AND Id = 50)

Upvotes: 2

AaronLS
AaronLS

Reputation: 38365

I think this might work for what you want.

  SELECT * FROM table Where id = 1 && @user == 'Bob'

Union

  SELECT * FROM table WHERE id = 50 && @animal == 'Cat' && @user == 'Bob'

Upvotes: 0

Martin
Martin

Reputation: 1213

IF (@user == 'Bob')
BEGIN
   SELECT * FROM table Where id = 1
END
ELSE IF (@animal == 'Cat') and (@user == 'Bob')
BEGIN
   SELECT * FROM table WHERE id = 50
END

Upvotes: 2

Related Questions