Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

SQL - How to convert varchar(255) to int

Posted on 2013-05-21
6
Medium Priority
?
1,247 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
Survive A High-Traffic Event with Percona

Your application or website rely on your database to deliver information about products and services to your customers. You can’t afford to have your database lose performance, lose availability or become unresponsive – even for just a few minutes.

 
LVL 7

Accepted Solution

by:
Ross Turner earned 1500 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

Survive A High-Traffic Event with Percona

Your application or website rely on your database to deliver information about products and services to your customers. You can’t afford to have your database lose performance, lose availability or become unresponsive – even for just a few minutes.

Question has a verified solution.

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

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.
Windocks is an independent port of Docker's open source to Windows.   This article introduces the use of SQL Server in containers, with integrated support of SQL Server database cloning.
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.
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function

715 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