Friday, May 11, 2012

SQL: Using case in where clause to check conditional column in select list

 

Today I had a colleague ask me how he could use a conditional column in a where clause.  At first I did not think it was possible, but then I started thinking about it and solved the issue by copying the case statement to the where clause.

 

Below is a simple query snippet I came up with to test it, and it worked!  Pretty cool..

   1: SELECT 
   2:     case myKey WHEN 205 THEN 'hello' ELSE 'goodbye' END AS 'testit', * 
   3: FROM 
   4:     myTable 
   5: WHERE 
   6:     case myKey WHEN 205 THEN 'hello' ELSE 'goodbye' END = 'hello'

No comments:

Post a Comment