locked
where clause question RRS feed

  • Question

  • Someone asked me whether you could use an 'if' statement in a 'where' clause.    I'm not wanting to get into the merits of whether you should do this or not (I would use a 'case' statement myself), but i was wondering if it was possible, and if so, can you provide a basic example.    Thanks
    Saturday, May 19, 2012 2:54 PM

Answers

  • Hello,

    A T-SQL a IF THEN/ELSE is a program flow command, you can't use it in a WHERE clause; you could only use a CASE WHEN statement.


    Olaf Helper
    * cogito ergo sum * errare humanum est * quote erat demonstrandum *
    Wenn ich denke, ist das ein Fehler und das beweise ich täglich
    Blog Xing

    • Proposed as answer by Naomi N Sunday, May 20, 2012 2:49 AM
    • Marked as answer by Kalman Toth Sunday, May 27, 2012 10:23 PM
    Saturday, May 19, 2012 3:03 PM

All replies

  • Hello,

    A T-SQL a IF THEN/ELSE is a program flow command, you can't use it in a WHERE clause; you could only use a CASE WHEN statement.


    Olaf Helper
    * cogito ergo sum * errare humanum est * quote erat demonstrandum *
    Wenn ich denke, ist das ein Fehler und das beweise ich täglich
    Blog Xing

    • Proposed as answer by Naomi N Sunday, May 20, 2012 2:49 AM
    • Marked as answer by Kalman Toth Sunday, May 27, 2012 10:23 PM
    Saturday, May 19, 2012 3:03 PM
  • Thanks Olaf.   Thats kind of what I thought, but I wanted to get a second opinion.
    Saturday, May 19, 2012 3:44 PM
  • Hi

    Good question I need to add it to my SQL Where clause tutorial.

    Below is an example:

    SELECT *
      FROM TableName
      where (case when datepart(WEEKDAY,getdate()) IN (7,1) then 1 else 0 end) = 1

    IF (using case) is handy for complex queries. I don't often use it using sql where but I do often use it with aggregate functions.

    Regards

    Emil


    Saturday, May 19, 2012 8:33 PM