将SQL Server中的varchar转换或转换为INT

时间:2017-05-23 11:12:09

标签: sql sql-server casting type-conversion

我正在尝试将以下内容转换为整数,以便我可以进行计算,从123.456.789123456789

然而,当我尝试

CAST([Total number] AS INT)

OR

CONVERT(int, [Total number])

然后我收到错误

  

将varchar值'123.456.789'转换为数据类型int。

时转换失败

4 个答案:

答案 0 :(得分:4)

假设点不是小数部分分割器且您的数字是整数(不是浮点数/小数) - 您可以在转换之前从字符串中删除点:

CAST(replace([Total number], '.', '') AS int)

答案 1 :(得分:4)

Declare @val varchar(100)='123.456.789'

SELECT CAST (REPLACE (@val,'.','') AS INT) As Intval

答案 2 :(得分:0)

你可以使用try_convert或try_cast,即使它有任何特殊字符,在这种情况下它会返回null

Select try_convert(int, replace([Total number], '.', ''))

答案 3 :(得分:0)

这是您的要求如下

 Declare @val TABLE (ID INT IDENTITY,Val varchar(100))

INSERT INTO @val
SELECT '356.345.789' UNION ALL
SELECT '123.456.333' UNION ALL
SELECT '444.124.444' UNION ALL
SELECT '347.456.555' UNION ALL
SELECT '123.666.789' UNION ALL
SELECT '678.432.789' UNION ALL
SELECT '789.456.111' UNION ALL
SELECT '123.457.123' UNION ALL
SELECT '333.111.789'


SELECT ROW_NUMBER()OVER(Order by (SELECT 1)) AS Rno, 
       CAST(REPLACE (Val,'.','') AS INT) As Intval 
FROM @val