Convert a string to int using sql query

后端 未结 4 1434
[愿得一人]
[愿得一人] 2020-12-07 12:08

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

相关标签:
4条回答
  • 2020-12-07 12:16

    You could use CAST or CONVERT:

    SELECT CAST(MyVarcharCol AS INT) FROM Table
    
    SELECT CONVERT(INT, MyVarcharCol) FROM Table
    
    0 讨论(0)
  • 2020-12-07 12:30

    Try this one, it worked for me in Athena:

    cast(MyVarcharCol as integer)
    
    0 讨论(0)
  • 2020-12-07 12:36

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

    SELECT TRY_PARSE(MyVarcharCol as int)
    
    SELECT TRY_CONVERT(int, MyVarcharCol)
    
    0 讨论(0)
  • 2020-12-07 12:40

    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
    
    0 讨论(0)
提交回复
热议问题