2

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?

3
  • 3
    What does "fails" mean? Commented Jul 17, 2013 at 13:48
  • 1
    Do you need them in one resultset? Commented Jul 17, 2013 at 13:53
  • Be aware that a batch/command/stored procedure can return multiple result sets. Each select statement will correspond to a result set. The way that your SQL is written, you will have at most 2 separate result sets, both containing either zero or one record. Is that what you want, or do you want the results in some other form? Commented Jul 17, 2013 at 13:58

5 Answers 5

2

I recommend a single statement:

SELECT
   *
FROM table
WHERE
    (@user = 'Bob' AND Id = 1)
    OR
    (@animal= 'Cat' AND Id = 50)
Sign up to request clarification or add additional context in comments.

9 Comments

ID has to be a result, not a selection value.
@Martin . . . Can you elaborate? Based on my reading of the question, this simplifies the logic and does what the OP wants.
@Gordon, the OP wants ID to be 50 if user = 'Bob' AND Animal = 'Cat' and ID to 1 if User = 'Bob'. This query does not do that. Based on his question i would suggest ELSE IF instead of two IF's.
@Martin, check the OP query, he's doing a SELECT * FROM table where id = 1
Sorry if my question was unclear but this is what i wanted, thanks very much
|
2
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

Comments

1
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

Comments

0

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'

Comments

-1

Try this nested if function:

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

2 Comments

sql server uses a different syntax
Could of just noted that, but hey, that's what the internet is for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.