SQL将char转换为数字

时间:2015-05-13 01:37:25

标签: sql sql-server sql-server-2008

我收到此错误:

  

转换varchar值时转换失败'这是一个FUTURES项目。 '到数据类型int。

CAST有什么问题?

UPDATE STOCK 
SET DESC2 = 'This is a FUTURES item. ' + LEFT(DESC1, 4) + 'futures will begin arriving in ' + (CAST(LEFT(DESC1, 4) as INT) + 3)
WHERE ISNUMERIC(LEFT(DESC1, 4)) = 1

1 个答案:

答案 0 :(得分:3)

运算符+已超载。当任何操作数是一个数字时,它将被视为加法。根据您的要求,您需要将值重新转换回字符串:

UPDATE STOCK
    SET DESC2 = 'This is a FUTURES item. ' + LEFT(DESC1, 4) + 'futures will begin arriving in ' + CAST(CAST(LEFT(DESC1, 4) as INT) + 3 as VARCHAR(255))
WHERE ISNUMERIC(LEFT(DESC1, 4)) = 1;

尽管此查询可能有效,但WHERE之前set没有保证(在SQL Server中)。这意味着您仍然可以获得类型转换错误。更新版本中的解决方案是try_convert()。或者,您可以使用case声明:

UPDATE STOCK
    SET DESC2 = 'This is a FUTURES item. ' + LEFT(DESC1, 4) + 'futures will begin arriving in ' +
                (CASE WHEN ISNUMERIC(LEFT(DESC1, 4)) = 1
                      THEN CAST(CAST(LEFT(DESC1, 4) as INT + 3) as VARCHAR(255))
                 END)
WHERE ISNUMERIC(LEFT(DESC1, 4)) = 1;