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 dencom on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

CASE in WHERE statement

Status
Not open for further replies.

thamms

MIS
Sep 13, 2007
44
ZA
Hi,

I am wondering if this is possible:

SELECT TOP 20 *,
CASE @Mode = 'Equity' THEN
Code IN ('ABC', 'CDE')
CASE @Mode = 'NonEquity' THEN
Code NOT IN ('ABC', 'CDE')
FROM #myTable
ORDER BY ABS(Ratio*100-100) DESC

Error:
Incorrect syntax near the keyword 'IN'.

Basically, I need the "WHERE clause" to change depending on the variable value. But I'm not sure where to stick the WHERE clause.

Most of the examples online are too simplistic.

Thanks
 
Oops my syntax is not right, even for this messed up example:

SELECT TOP 20 *,
CASE
WHEN @Mode = 'Equity'
THEN StCode IN('ABC', 'CDE')
WHEN @Mode = 'NonEquity'
THEN StCode IN ('ABC', 'CDE')
FROM #myTable
ORDER BY abs(Ratio*100-100) DESC
 
I don't think you need to use Case/When. Simple boolean logic should do it.

Code:
Select Top 20 *
From   #myTable
Where  (@Mode = 'Equity' And Code In ('ABC','CDE'))
       Or (@Mode = 'NonEquity' And Code Not In ('ABC','CDE')
ORDER BY ABS(Ratio*100-100) DESC


-George

"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
Of course, I missed a closing parenthesis.

Code:
Select Top 20 *
From   #myTable
Where  (@Mode = 'Equity' And Code In ('ABC','CDE'))
       Or (@Mode = 'NonEquity' And Code Not In ('ABC','CDE')[!])[/!]
ORDER BY ABS(Ratio*100-100) DESC


-George

"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top