Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string to int using sql query

How to convert a string to integer using SQL query on SQL Server 2005?

like image 393
Rahul Vyas Avatar asked Apr 08 '09 07:04

Rahul Vyas


People also ask

Can we convert string to int in SQL?

CAST and CONVERT can be used to convert a string to a number of any data type. For example, you can convert a string to a number of data type INTEGER. TO_DATE converts a formatted date string to a date integer. TO_TIMESTAMP converts a formatted date and time string to a standard timestamp.

What is CAST function in SQL?

SQL Server CAST() Function The CAST() function converts a value (of any type) into a specified datatype. Tip: Also look at the CONVERT() function.


2 Answers

You could use CAST or CONVERT:

SELECT CAST(MyVarcharCol AS INT) FROM Table  SELECT CONVERT(INT, MyVarcharCol) FROM Table 
like image 73
Christian C. Salvadó Avatar answered Oct 21 '22 11:10

Christian C. Salvadó


Also be aware that when converting from numeric string ie '56.72' to INT you may come up against a SQL error.

Conversion failed when converting the varchar value '56.72' to data type int. 

To get around this just do two converts as follows:

STRING -> NUMERIC -> INT

or

SELECT CAST(CAST (MyVarcharCol AS NUMERIC(19,4)) AS INT) 

When copying data from TableA to TableB, the conversion is implicit, so you dont need the second convert (if you are happy rounding down to nearest INT):

INSERT INTO TableB (MyIntCol) SELECT CAST(MyVarcharCol AS NUMERIC(19,4)) as [MyIntCol] FROM TableA 
like image 34
Steven de Salas Avatar answered Oct 21 '22 10:10

Steven de Salas