Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Evaluate multiple expressions in case when

Status
Not open for further replies.

MrGandalf

Programmer
Jul 19, 2005
35
NL
Hi all,

How can I use multiple (boolean) expressions in the where clause? For example:

Select *
From Client
Where case when age>18
then redhair and blueeyes
else blond and greeneyes
end = 1

This gives an error. Can I write in another way?



 
For that example you could use:

Code:
SELECT * FROM client
WHERE (age > 18
  AND hair = 'red'
  AND eyes = 'blue')
  OR (age <= 18
  AND hair = 'blonde'
  AND eyes = 'green')

--James
 
The case clause must be in the select part of he statement

eg

select case when 1 then 'AAA' else 'BBB' end as field1, field2
from my table
where bla bla bla

Mo
 
Mo,

Says who? The CASE works just fine in the WHERE clause. I know because I have a couple of scripts that run each day using CASE in the WHERE.

-SQLBill

Posting advice: FAQ481-4875
 
Indeed the case statement can be used in a where clause.

JamesLean. Tx for your input. It is an other way of writing it but I want to keep the CASE WHEN statement.
This is because my actual SQL has nested CASE statements. For each nesting (n) I would have to write 2n OR statements. Isn't it possible to keep the CASE statement?

 
What error are you getting with this? Syntax or other?



Catadmin - MCDBA, MCSA
"If a person is Microsoft Certified, does that mean that Microsoft pays the bills for the funny white jackets that tie in the back???
 
CatAdmin. the error: Incorrect syntax near the keyword 'and'

When I try this (without the AND):

Select *
From Client
Where case when age>18
then redhair
else blond
end = 1

it doesn't give an error and returns the result.
 
This could work:

Code:
Select *
From Client
Where case when age>18
      then redhair
      else blond
      end = 1
and   case when age>18
      then blueeyes
      else greeneyes
      end = 1

Tim
 
Hi all. I have been following this post. What is the end = 1 syntax? I have never seen that.

Thanks.... Jim
 
Jim,

the = 1 is the continuation of the where statement and is outside of the case statement. In the case of my post, if the age of a record was 20 the select statement would look like this, without the case statement:

Select *
From Client
Where redhair = 1
and blueeyes = 1

Tim

 
Tim,

Thanks.. took me a little but now I got it. Thanks for the explination.

Jim
 
Tx Patty, will give you the credits. Although i find it a limitation that I can't use multiple boolean expression in a CASE WHEN. e.g. CASE WHEN Y THEN X AND Y...

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top