Solved

SQL - How to convert varchar(255) to int

Posted on 2013-05-21
6
1,182 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
Free eBook: Backup on AWS

Everything you need to know about backup and disaster recovery with AWS, for FREE!

 
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 48

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

Back Up Your Microsoft Windows Server®

Back up all your Microsoft Windows Server – on-premises, in remote locations, in private and hybrid clouds. Your entire Windows Server will be backed up in one easy step with patented, block-level disk imaging. We achieve RTOs (recovery time objectives) as low as 15 seconds.

Question has a verified solution.

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

Suggested Solutions

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
In the first part of this tutorial we will cover the prerequisites for installing SQL Server vNext on Linux.
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
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

739 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