Solved

SQL - How to convert varchar(255) to int

Posted on 2013-05-21
6
1,203 Views
Last Modified: 2013-05-21
Hi.

I have a parameter @p1 = '1,2,3,4'
and I want to convert it to an int, so that I can query :

where PersonID in (@p1).

I tried :

where PersonID in cast(@p1  as int), but I get the following error:

"Conversion failed when converting the varchar value '1,2,3,4' to data type int."

Can anyone help me fix this?
0
Comment
Question by:Jasmin01
[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
6 Comments
 
LVL 9

Expert Comment

by:mimran18
ID: 39183691
0
 
LVL 7

Expert Comment

by:Ross Turner
ID: 39183695
if you want to convert it into a int remove the commas.
but you will get 1234 if that what you are after

Cast(replace(@p1,',','') as int)
0
 
LVL 11

Expert Comment

by:lenordiste
ID: 39183703
Hi Jasmin01,

this happens because you are trying to cast into a single int value the whole varchar '1,2,3,4'. What you would want to do is to actually "split" those values or use a whole different structure in your parameter.

There are many solutions depending on your SQL Server version which I invite you to read through:
http://www.sommarskog.se/arrays-in-sql-2005.html#CSV
http://www.sommarskog.se/arrays-in-sql-2008.html

Good luck!
0
Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

 
LVL 7

Accepted Solution

by:
Ross Turner earned 500 total points
ID: 39183709
Using mimran18 suggestion i knocked up this example for you, i got the wrong end of the stick apparently i need more coffee

http://sqlfiddle.com/#!3/17b13/1

CREATE TABLE #TempTable (
	ID INT,
	NAME VARCHAR(30)
	)

INSERT INTO #temptable
VALUES (
	1,
	'Ross'
	),
	(
	2,
	'bob'
	),
	(
	3,
	'james'
	),
	(
	4,
	'alex'
	),
	(
	5,
	'steven'
	)

DECLARE @Xml AS XML
DECLARE @WhereClause VARCHAR(MAX)

SET @WhereClause = '1,2,3,4'
SET @Xml = cast(('<A>' + replace(@WhereClause, ',', '</A><A>') + '</A>') AS XML)

SELECT *
FROM #TempTable
WHERE #TempTable.ID IN (
		SELECT A.value('.', 'varchar(max)') AS [Column]
		FROM @Xml.nodes('A') AS FN(A)
		)

Open in new window

0
 

Author Closing Comment

by:Jasmin01
ID: 39183713
Thanks
0
 
LVL 49

Expert Comment

by:PortletPaul
ID: 39183722
The basic issue here is you can't just convert that parameter to int (and get the wanted results that is). Your parameter is a string that just happens to look like a set of integers separated by commas: '1,2,3,4,5' ; but it is still ONE STRING of characters.

if you are evaluating an integer field against this string via IN(), you not only need to convert to int, but you also need to divide the ONE STRING into MANY INT values, hence you must apply a technique such as the ones in the above URL. e.g. using the XML approach:
DECLARE @p1 varchar(max)
declare @Splitter char(1)
SET @Splitter = ','

SET @p1 = '2,3,4,5'


;WITH
SplitPersons AS(
  SELECT CAST('<v>' + REPLACE(@p1, @Splitter, '</v><v>') + '</v>' AS XML) AS Split
),
persons as (
  select 1 as personID, 11 as whatever union all
  select 2 as personID, 22 as whatever union all
  select 3 as personID, 33 as whatever union all
  select 4 as personID, 44 as whatever union all
  select 5 as personID, 55 as whatever union all
  select 6 as personID, 66 as whatever union all
  select 7 as personID, 77 as whatever union all
  select 8 as personID, 88 as whatever union all
  select 9 as personID, 99 as whatever 
  )
select
*
from persons
where (@p1 is null
       or
       personID IN (
 
                            SELECT cast(x.v.value('.', 'bigint') as bigint) AS Value
                            FROM SplitPersons
                            CROSS APPLY Split.nodes('//v') x(v)
                         )
       )

Open in new window

This assumes those parameters will only every carry digits and the delimiter (comma). i.e. if you put bad characters into the parameters the query would fail and don't use a delimiter that would "disturb XML" like a > or < (not that you are likely to).

You should also take care that your parameters should not start with a comma.

I think its also worth mentioning that this xml based approach is also based on the assumption you are not selecting thousands of items, instead I hope you are likely to be selecting a relatively small number of these. Please test against the largest likely selections of these to ensure performance is acceptable.

These are useful references if you need more information or want to explore this parameter issue more deeply:

an often cited reference on this split string topic:
http://www.sommarskog.se/arrays-in-sql.html

useful introduction to the background of this issue, and some alternative methods for handling it
http://www.sqlperformance.com/2012/07/t-sql-queries/split-strings
0

Featured Post

[Webinar] How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them. Thursday, July 13, 2017 10:00 A.M. PDT

Question has a verified solution.

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

I have a large data set and a SSIS package. How can I load this file in multi threading?
It is possible to export the data of a SQL Table in SSMS and generate INSERT statements. It's neatly tucked away in the generate scripts option of a database.
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.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

635 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