Solved

Select with case in a "WHERE"

Posted on 2014-09-19
2
167 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
[X]
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
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

Three Reasons Why Backup is Strategic

Backup is strategic to your business because your data is strategic to your business. Without backup, your business will fail. This white paper explains why it is vital for you to design and immediately execute a backup strategy to protect 100 percent of your data.

Question has a verified solution.

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

Suggested Solutions

Introduction SQL Server Integration Services can read XML files, that’s known by every BI developer.  (If you didn’t, don’t worry, I’m aiming this article at newcomers as well.) But how far can you go?  When does the XML Source component become …
Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

730 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