0

I have a way too big query using only SELECT, and I need to filter it using conditional clause WHERE. Something like this :

if (mycondition)

    set @strwhere='conditionalexpression_1'
else

    set @strwhere='conditionalexpression_2'

.. then I want to use @strwhere in WHERE, like this :

SELECT col1, col2, col3 ............
 from tablex where @strwhere

Does any way to do it ? I have tried but... nothing works fine!

7
  • Do you want to use dynamic SQL? Commented Sep 11, 2014 at 3:33
  • It is possible to use only dynamic WHERE? Commented Sep 11, 2014 at 3:34
  • @parameters will not work like that; but are you using php or C#, you could do the substitutions there - or you have to use dynamic sql (with risks of sql injection to consider) Commented Sep 11, 2014 at 3:40
  • sorry what dbms type is it? MySQL or SQL Server Commented Sep 11, 2014 at 3:41
  • what condition will your IF have? Will it have if condition on same table tablex? Commented Sep 11, 2014 at 4:43

1 Answer 1

1

Do like this, build the full query first and the execute.

SET@SQLQuery='SELECT col1, col2, col3 from tablex where '
If (mycondition)

    set @SQLQuery=@SQLQuery + 'conditionalexpression_1'
else

    set @SQLQuery=@SQLQuery + 'conditionalexpression_2'

EXECUTE(@SQLQuery)
Sign up to request clarification or add additional context in comments.

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.