将varchar转换为int时转换失败

时间:2014-03-14 15:04:31

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

我在SQL中收到转换错误。我已尝试将Casting和Convert转换为int但失败了。

SELECT 
    ProdId, ParentCat, ProdFullName, ProdImage 
FROM 
    Product
WHERE
    ProdId IN (SELECT Compared FROM Product WHERE ProdId = 10803)
  • ProdIdint
  • Compared列为varchar

Compared列值为:

32879, 10844, 10747, 81113, 8001, 81469

3 个答案:

答案 0 :(得分:1)

SELECT 
    ProdId, ParentCat, ProdFullName, ProdImage 
FROM 
    Product
WHERE
    ProdId IN (SELECT convert(int,ltrim(rtrim(Compared))) 
              FROM Product WHERE ProdId = 10803)

详细了解CAST and CONVERT

答案 1 :(得分:0)

在这种情况下,您只需将ProdId转换为varchar。

WHERE
CAST(ProdId AS varchar(10)) IN (SELECT Compared FROM Product WHERE ProdId = 10803)

答案 2 :(得分:0)

在这种情况下,您应该将查询构建为字符串并执行它 DECLARE @query VARCHAR(MAX) SELECT @query = 'SELECT ProdId, ParentCat, ProdFullName, ProdImage FROM Product WHERE ProdId IN (' + Compared + ')' FROM Product WHERE ProdId = 10803 EXEC (@query)