Solved

Select with case in a "WHERE"

Posted on 2014-09-19
2
161 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:ScottPletcher
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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Join & Write a Comment

Everyone has problem when going to load data into Data warehouse (EDW). They all need to confirm that data quality is good but they don't no how to proceed. Microsoft has provided new task within SSIS 2008 called "Data Profiler Task". It solve th…
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
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…

746 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

11 Experts available now in Live!

Get 1:1 Help Now