0

I cannot find an answer to this seemingly easy problem. I need to execute a different SELECT statement based on a condition.

A simple example :

if <condition>

SELECT id FROM table;

otherwise

SELECT id FROM table WHERE variable=1;

In other words I need to add an additional WHERE clause depending on the condition, however the problem boils down to choosing a different SELECT clause based on whether the condition is true or false.

3
  • What means condition? Commented Aug 13, 2014 at 18:38
  • In my case its a EXISTS ( subquery ) clause. Commented Aug 13, 2014 at 18:40
  • could you please put the example of condition? It would be better then ofcourse. Commented Aug 13, 2014 at 19:17

2 Answers 2

1
SELECT id FROM table WHERE variable=1 OR <condition>
Sign up to request clarification or add additional context in comments.

Comments

0

case statements can be used as well...

SELECT id FROM table
where case when variable is not null then variable else 1 end
=
case when variable is not null then @variable else 1 end

You'll probably want different logic in the case statements, but this is saying when variable has a value (not null) then use the where clause variable = @variable, else 1=1 (which brings back all rows / no filter).

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.