?
Solved

Select with case in a "WHERE"

Posted on 2014-09-19
2
Medium Priority
?
169 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 2000 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

Get your Disaster Recovery as a Service basics

Disaster Recovery as a Service is one go-to solution that revolutionizes DR planning. Implementing DRaaS could be an efficient process, easily accessible to non-DR experts. Learn about monitoring, testing, executing failovers and failbacks to ensure a "healthy" DR environment.

Question has a verified solution.

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

This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
Ready to get certified? Check out some courses that help you prepare for third-party exams.
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

765 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