Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Select with case in a "WHERE"

Posted on 2014-09-19
2
165 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

U.S. Department of Agriculture and Acronis Access

With the new era of mobile computing, smartphones and tablets, wireless communications and cloud services, the USDA sought to take advantage of a mobilized workforce and the blurring lines between personal and corporate computing resources.

Question has a verified solution.

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

Nowadays, some of developer are too much worried about data. Who is using data, who is updating it etc. etc. Because, data is more costlier in term of money and information. So security of data is focusing concern in days. Lets' understand the Au…
When you hear the word proxy, you may become apprehensive. This article will help you to understand Proxy and when it is useful. Let's talk Proxy for SQL Server. (Not in terms of Internet access.) Typically, you'll run into this type of problem w…
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

839 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