all groups > sql server programming > february 2005 >
You're in the

sql server programming

group:

How to make a safe varchar() to int conversion


How to make a safe varchar() to int conversion Nevyn Twyll
2/1/2005 7:57:46 PM
sql server programming:
I'm selecting a big group of records for output, and I need to convert a
couple columns from varchar to int. (SELECT CAST(mycharfield as int) as
myintfield from ....)

Problem is, some erroneous data has non-numeric characters in it, and SQL
Server kills the whole SELECT, outputting no rows (!!!).

Is there any way to get SQL to just put NULL or 0 in for erroneous data -
the way you can use SET ARITHABORT to have it ignore numeric errors and keep
processing?

Thanks!

- Nevyn

Re: How to make a safe varchar() to int conversion Aaron Weiker
2/1/2005 8:12:38 PM
Hello Nevyn,
One of the best way's I've found to do this is to use a LIKE clause in your
select statement

SELECT * FROM myTable WHERE numCol NOT LIKE '%[a-z]%'

--
Aaron Weiker
http://aaronweiker.com/
http://sqlprogrammer.org/

[quoted text, click to view]


Re: How to make a safe varchar() to int conversion oj
2/1/2005 9:09:58 PM
You can just add

"where isnumeric(col)=1"
or
"where col like '%[^0-9]%'"

to your query

--
-oj


[quoted text, click to view]

Re: How to make a safe varchar() to int conversion oj
2/2/2005 11:32:30 PM
Tks for the correction.


--
-oj


[quoted text, click to view]

Re: How to make a safe varchar() to int conversion Gert-Jan Strik
2/2/2005 11:56:16 PM
That would be "where col NOT like '%[^0-9]%'"

Gert-Jan


[quoted text, click to view]
AddThis Social Bookmark Button