Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Comma separated integer value in query

Author  Topic 

razeena
Yak Posting Veteran

54 Posts

Posted - 2012-12-18 : 02:14:35
Hi,
-------------
Declare @l1 varchar(10)= '4,5'
Select
Col1,
Col2
From
<tableName>
Where
Col3 in (@l1)
-----
Col3 is an integer value
This is showing error as "Conversion failed when converting the varchar value '4,5' to data type int."
What I needed was
---
Select
Col1,
Col2
From
<tableName>
Where
Col3 in (4,5)
--------
Any ideas about how to pass the argument?

bandi
Master Smack Fu Yak Hacker

2242 Posts

Posted - 2012-12-18 : 02:17:34
Use this condition

WHERE ',' + @l1 + ',' LIKE '%,' + CAST(Col3 AS varchar) + ',%'

--
Chandu
Go to Top of Page

Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)

7020 Posts

Posted - 2012-12-18 : 11:00:20
quote:
Originally posted by razeena

Hi,
-------------
Declare @l1 varchar(10)= '4,5'
Select
Col1,
Col2
From
<tableName>
Where
Col3 in (@l1)
-----
Col3 is an integer value
This is showing error as "Conversion failed when converting the varchar value '4,5' to data type int."
What I needed was
---
Select
Col1,
Col2
From
<tableName>
Where
Col3 in (4,5)
--------
Any ideas about how to pass the argument?



You can use a split function to parse the comma delimited list into a temp table and then use that in your query.

The function on the link below should do the job.
Tally OH! An Improved SQL 8K “CSV Splitter” Function
http://www.sqlservercentral.com/articles/Tally+Table/72993/





CODO ERGO SUM
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-12-19 : 01:00:09
quote:
Originally posted by bandi

Use this condition

WHERE ',' + @l1 + ',' LIKE '%,' + CAST(Col3 AS varchar) + ',%'

--
Chandu


can cause performance hit in case of large datasets. Also in case Col3 contain spaces or other characters that has to be handled as well

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

bandi
Master Smack Fu Yak Hacker

2242 Posts

Posted - 2012-12-19 : 01:04:45
quote:
Originally posted by visakh16
WHERE ',' + @l1 + ',' LIKE '%,' + CAST(Col3 AS varchar) + ',%'
can cause performance hit in case of large datasets. Also in case Col3 contain spaces or other characters that has to be handled as well


hmm. Thanks for your suggestion visakh

--
Chandu
Go to Top of Page
   

- Advertisement -