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
Solved

SQL - How to convert varchar(255) to int

Posted on 2013-05-21
6
1,163 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
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
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

NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

Question has a verified solution.

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

Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
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 set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.

839 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