Convert a string to int using sql query

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

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

4条回答
  •  轻奢々
    轻奢々 (楼主)
    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
    

提交回复
热议问题