Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Varchar to Int in sql server 2008?

How to convert Varchar to Int in sql server 2008.

i have following code when i tried to run it wont allowed me to convert Varchar to Int.

Select Cast([Column1] as INT) 

Column1 is of Varchar(21) NOT NULL type and i wanted to convert it into Int. actually i am trying to insert Column1 into another table having Field as INT. can someone please help me to convert this ?

like image 888
Vikrant More Avatar asked Nov 01 '11 21:11

Vikrant More


2 Answers

Spaces will not be a problem for cast, however characters like TAB, CR or LF will appear as spaces, will not be trimmed by LTRIM or RTRIM, and will be a problem.

For example try the following:

declare @v1 varchar(21) = '66',
        @v2 varchar(21) = '   66   ',
        @v3 varchar(21) = '66' + char(13) + char(10),
        @v4 varchar(21) = char(9) + '66'

select cast(@v1 as int)   -- ok
select cast(@v2 as int)   -- ok
select cast(@v3 as int)   -- error
select cast(@v4 as int)   -- error

Check your input for these characters and if you find them, use REPLACE to clean up your data.


Per your comment, you can use REPLACE as part of your cast:

select cast(replace(replace(@v3, char(13), ''), char(10), '') as int)

If this is something that will be happening often, it would be better to clean up the data and modify the way the table is populated to remove the CR and LF before it is entered.

like image 92
Jeff Ogata Avatar answered Oct 31 '22 05:10

Jeff Ogata


you can use convert function :

Select convert(int,[Column1])
like image 43
Ali Rasouli Avatar answered Oct 31 '22 07:10

Ali Rasouli