Convert a string to int using sql query

SqlSql Server-2005

Sql Problem Overview


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

Sql Solutions


Solution 1 - Sql

You could use CAST or CONVERT:

SELECT CAST(MyVarcharCol AS INT) FROM Table

SELECT CONVERT(INT, MyVarcharCol) FROM Table

Solution 2 - Sql

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

Solution 3 - Sql

Starting with SQL Server 2012, you could use TRY_PARSE or TRY_CONVERT.

SELECT TRY_PARSE(MyVarcharCol as int)

SELECT TRY_CONVERT(int, MyVarcharCol)

Solution 4 - Sql

Try this one, it worked for me in Athena:

cast(MyVarcharCol as integer)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRahul VyasView Question on Stackoverflow
Solution 1 - SqlChristian C. SalvadóView Answer on Stackoverflow
Solution 2 - SqlSteven de SalasView Answer on Stackoverflow
Solution 3 - SqlÖrjan JämteView Answer on Stackoverflow
Solution 4 - Sqlashutosh singhView Answer on Stackoverflow