Solved

SQL - How to convert varchar(255) to int

Posted on 2013-05-21
6
1,105 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
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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
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

Backup Your Microsoft Windows Server®

Backup 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.

Join & Write a Comment

I wrote this interesting script that really help me find jobs or procedures when working in a huge environment. I could I have written it as a Procedure but then I would have to have it on each machine or have a link to a server-related search that …
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
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.

707 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

18 Experts available now in Live!

Get 1:1 Help Now