“CASE” statement within “WHERE” clause in SQL Server 2008

First off, the CASE statement must be part of the expression, not the expression itself.

In other words, you can have:

WHERE co.DTEntered = CASE 
                          WHEN LEN('blah') = 0 
                               THEN co.DTEntered 
                          ELSE '2011-01-01' 
                     END 

But it won’t work the way you have written them eg:

WHERE 
    CASE LEN('TestPerson')
        WHEN 0 THEN co.personentered  = co.personentered
   ELSE co.personentered LIKE '%TestPerson'
    END 

You may have better luck using combined OR statements like this:

WHERE (
        (LEN('TestPerson') = 0 
             AND co.personentered = co.personentered
        ) 
        OR 
        (LEN('TestPerson') <> 0 
             AND co.personentered LIKE '%TestPerson')
      )

Although, either way I’m not sure how great of a query plan you’ll get. These types of shenanigans in a WHERE clause will often prevent the query optimizer from utilizing indexes.

Leave a Comment