Solved

TSQL "IN" fails when parameter is comma separated

Posted on 2011-03-18
4
448 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
  • 2
4 Comments
 
LVL 32

Expert Comment

by:ewangoya
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:
ewangoya 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 142

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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

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.
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

705 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

20 Experts available now in Live!

Get 1:1 Help Now