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

Can you use a CASE in a WHERE statement.

Status
Not open for further replies.

macmac1

Programmer
Jan 20, 2002
11
US
Hi all,

I am trying to do the following.

Pass a value in to my SP.
Based on that value use the condition.

----------------------------------------
WHERE
CASE
WHEN @switch = 1 THEN ( r.id in (@rep) and (m.merchant_active=1))
ELSE (m.merchant_alias in (@merchant_alias) and (m.merchant_active=1))
END
 
You can't do it exactly that way. You must name the columns in the Where clause. They cannot be inside the CASE Function. You can do something like this.

...
WHERE m.merchant_active=1
And r.id=
CASE WHEN @switch = 1
THEN @rep
Else r.id
End
And m.merchant_alias=
CASE WHEN @switch <> 1
THEN @merchant_alias
Else m.merchant_alias
End

If you don't want to do it this way, you can create and execute a dynamic SQL statement.

Declare @sql varchar(400)

Set @sql='Select * From table1 r' +
' Join table2 m On r.id=m.id' +
' Where m.merchant_active=1'

If @swicth=1
Set @sql=@sql+' And r.id=' + str(@rep)
Else
Set @sql=@sql+' And m.merchant_alias=' + @merchant_alias

Exec(@sql) Terry L. Broadbent - DBA
Computing Links:
faq183-874 contains &quot;Suggestions for Getting Quick and Appropriate Answers&quot; to your questions.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top