Solved

TSQL "IN" fails when parameter is comma separated

Posted on 2011-03-18
4
483 Views
Last Modified: 2012-05-11
SELECT with IN clause failes when values are comma separated....

DECLARE @MYVAR AS Varchar(50)
SET @MYVAR = 'FL, AK, NY, CA'

SELECT * FROM MYTABLE
WHERE
(@MYVAR IS NULL OR [State] = @MYVAR)
0
Comment
Question by:Internet_Engineer
[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
4 Comments
 
LVL 32

Expert Comment

by:Ephraim Wangoya
ID: 35168518
Try this way

DECLARE @MYVAR AS Varchar(50)
SET @MYVAR = 'FL, AK, NY, CA'

SELECT * FROM MYTABLE
WHERE @MYVAR IS NULL
OR [State] IN (@MYVAR)
0
 
LVL 32

Accepted Solution

by:
Ephraim Wangoya earned 500 total points
ID: 35168553
or

Try this way

DECLARE @MYVAR AS Varchar(50)
SET @MYVAR = 'FL, AK, NY, CA'

SELECT * FROM MYTABLE
WHERE @MYVAR IS NULL
OR CHARINDEX([State], @MYVAR, 1) > 0
0
 

Author Closing Comment

by:Internet_Engineer
ID: 35168583
GREAT
0
 
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 35168951
please check out this article, it has more performant options:
http://www.experts-exchange.com/A_1536.html
0

Featured Post

MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

Question has a verified solution.

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

Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
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.
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed

759 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