SQL 使用sql查询将字符串转换为int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/728833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert a string to int using sql query
提问by Rahul Vyas
How to convert a string to integer using SQL query on SQL Server 2005?
如何在 SQL Server 2005 上使用 SQL 查询将字符串转换为整数?
回答by CMS
You could use CAST or CONVERT:
您可以使用CAST 或 CONVERT:
SELECT CAST(MyVarcharCol AS INT) FROM Table
SELECT CONVERT(INT, MyVarcharCol) FROM Table
回答by Steven de Salas
Also be aware that when converting from numeric string ie '56.72'
to INT you may come up against a SQL error.
另请注意,当从数字字符串 ie 转换'56.72'
为 INT 时,您可能会遇到 SQL 错误。
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
字符串 -> 数字 -> 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):
将数据从 TableA 复制到 TableB 时,转换是隐式的,因此您不需要第二次转换(如果您愿意向下舍入到最接近的 INT):
INSERT INTO TableB (MyIntCol)
SELECT CAST(MyVarcharCol AS NUMERIC(19,4)) as [MyIntCol]
FROM TableA
回答by ?rjan J?mte
Starting with SQL Server 2012, you could use TRY_PARSEor TRY_CONVERT.
从 SQL Server 2012 开始,您可以使用TRY_PARSE或TRY_CONVERT。
SELECT TRY_PARSE(MyVarcharCol as int)
SELECT TRY_CONVERT(int, MyVarcharCol)
回答by ashutosh singh
Try this one, it worked for me in Athena:
试试这个,它在雅典娜对我有用:
cast(MyVarcharCol as integer)