243

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

5 Answers 5

406

You could use CAST or CONVERT:

SELECT CAST(MyVarcharCol AS INT) FROM Table

SELECT CONVERT(INT, MyVarcharCol) FROM Table
Sign up to request clarification or add additional context in comments.

5 Comments

How do I catch/prevent the exception when one of the fields is non-numeric? I would have expected it to convert to 0.
Found it: select CASE WHEN ISNUMERIC('x') = 1 THEN CAST('x' AS INT) ELSE 0 END
Just a word: IsNumeric() can produce some perverse results. It will return TRUE for the string "-.", which will still cause an error when you try to cast it to a number.
IsNumeric will be true for strings with "-" only if the string is numeric for example "-5" or "-20", it will be false for strings like "5-", "-2-1". So if isNumeric() is true then conversion should not throw any exception
Now with SQL Server 2016+ you have TRY_CAST() that returns null if cast is not possible
33

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

SELECT TRY_PARSE(MyVarcharCol as int)

SELECT TRY_CONVERT(int, MyVarcharCol)

1 Comment

Definitely not the right answer for the original question since it was in relation to SQL Server 2005, but since it is 2019 and fewer folks are strapped to such an old version of SQL Server, this answer is definitely helpful.
22

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

Comments

0

Try this one, it worked for me in Athena:

cast(MyVarcharCol as integer)

Comments

0

Use the below query:

select to_number('String') from dual;

1 Comment

'to_number' is not a recognized built-in function name

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.