1

I want to create a statement like the following:

if (select statement1 returns rows){
   select statement2
}
else {
  select statement3
}

This if statement is part of a bigger query

   select from products where p.id in (
        if (select statement1 returns rows){
           select statement2
       }
       else {
        select statement3
      }

Is this possible in SQL Server, or is my thinking incorrect?

2
  • 3
    I presume you are wanting to run this against a database using C#? Commented Mar 6, 2013 at 19:36
  • What is the context of this select statement? Are you testing for an optional parameter in a stored procedure? Commented Mar 6, 2013 at 19:47

4 Answers 4

3

You need to use a combination of EXISTS and CASE..END:

select *
from products
where p.id in (
  case when (exists ( <statement1> ))
    then ( <statement2> )
    else ( <statement3> )
  end
)

Where <statement1> might be: SELECT * FROM Customer WHERE Id = 123

<statement2> might be: SELECT MIN(field) FROM someTable

<statement3> might be: SELECT 0 as DefaultValue

If you can show some examples of what you want those actual statements to be I can provide a more concrete answer.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks! thats all i needed to get started. the inner queries were confusing in my case but i figured them out.
1

Actually SQL is more rigid, due to performance considerations. Your query will look more like this:

select *
from products
where  1 = case when (exists ( <statement1> ))
              then case when p.id in ( <statement2> ) then 1 else 0 end
              else case when p.id in ( <statement3> ) then 1 else 0 end
           end

Comments

1

Since you are checking for the same id existance, I think you could do a UNION here.

select *
from products 
where p.id in  (select id from table1
                union 
                select id from table2)

Comments

1

I'd recommend using a UNION between your two conditions to help avoid performance problems...and may be easier to read as well.

    SELECT FROM products p
    WHERE EXISTS (SELECT STATEMENT1)
    AND EXISTS (SELECT STATEMENT2 s2 WHERE s2.p_id = p.id)
    UNION
    SELECT FROM products p
    WHERE NOT EXISTS (SELECT STATEMENT1)
    AND EXISTS (SELECT STATEMENT3 s3 WHERE s3.p_id = p.id)    

Depending on the nature of the statements, you might be able to leave off the Not Exists in the second select.

Comments

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.