0

I've a query like this one:

SELECT IF(@param = 42, 'static', SELECT ... );

But it doesn't work because I can't insert a SELECT statement inside a IF(). My problem is that I can't do otherwise (use an if-then statement outside sql) because to "architecture restrictions".

Any solution to select if evaluate or not a query based to parameter value?

1
  • Is the second select static? In that case you can just move the IF inside the query. If ... is foo FROM bar you get SELECT (case when @param = 42 then 'static' else foo end) FROM bar. Commented Oct 6, 2014 at 12:11

1 Answer 1

2

You don't need a select:

select (case when @param = 42 then 'static' else date_format(now(), '%Y-%m-%d') end)

Note that you are trying to mix two different types -- a datetime and string. You should explicitly convert the datetime to a string, using your preferred format.

You can write this with if(). case is slightly more general and the ANSI standard.

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

2 Comments

My fault. I need to run a generic query, not only a now(). It only was for a short example.
@Alvins . . . If you need the subquery, put it in parentheses.

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.