Solved

Select with case in a "WHERE"

Posted on 2014-09-19
2
163 Views
Last Modified: 2014-09-19
I'm trying to run a select statement and want the where clause to use different criteria depending on the value of a variable.  When I run the below I get an error
     Msg 102, Level 15, State 1, Line 9
     Incorrect syntax near '='.

Can I not do that in a where clause?


declare @Itemtype varchar(1)
set @Itemtype='1'

select 'pop30110',iv1.*
from pop30110 iv1
join dynamics_ext.dbo.tmpinvalid tmp on tmp.itemnmbr=iv1.itemnmbr
--where tmp.itemtype=@itemtype
--where tmp.itemtype ='1'
where (case when @Itemtype='' then tmp.itemtype ='1' else tmp.itemtype=@itemtype end )
0
Comment
Question by:jdr0606
2 Comments
 
LVL 34

Accepted Solution

by:
Brian Crowe earned 500 total points
ID: 40333864
select 'pop30110',iv1.*
from pop30110 iv1
join dynamics_ext.dbo.tmpinvalid tmp on tmp.itemnmbr=iv1.itemnmbr
WHERE (@itemtype = '' AND tmp.itemtype = '1')
   OR (@itemtype <> '' AND tmp.itemtype = @itemtype)
0
 
LVL 69

Expert Comment

by:Scott Pletcher
ID: 40333879
Much better query optimization by just making sure that @itemtype is never '':

declare @Itemtype varchar(1)
 set @Itemtype='1'
if @Itemtype = ''
    set @Itemtype = '1'

select ...
where tmp.itemtype = @itemtype
0

Featured Post

[Webinar] Disaster Recovery and Cloud Management

Learn from Unigma and CloudBerry industry veterans which providers are best for certain use cases and how to lower cloud costs, how to grow your Managed Services practice in IaaS clouds, and how to utilize public cloud for Disaster Recovery

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Having an SQL database can be a big investment for a small company. Hardware, setup and of course, the price of software all add up to a big bill that some companies may not be able to absorb.  Luckily, there is a free version SQL Express, but does …
I have a large data set and a SSIS package. How can I load this file in multi threading?
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
Viewers will learn how the fundamental information of how to create a table.

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

29 Experts available now in Live!

Get 1:1 Help Now