在SQL中接收数据类型转换错误

时间:2018-11-29 13:31:36

标签: sql sql-server tsql

我收到以下错误:

  

将数据类型varchar转换为数字时出错

对于以下代码:

  • a.name具有char数据类型,
  • b.type是字符,
  • c.sign是nchar和
  • d.amount是数字
 case when a.name='abc' and b.type='X' and c.sign='+' then 1*(d.amount)

2 个答案:

答案 0 :(得分:2)

此行未引起您的问题:

case when a.name = 'abc' and b.type = 'X' and c.sign = '+'
     then 1*(d.amount)

因为所有类型都被正确使用。可能发生的情况是case表达式中的另一个路径返回一个字符串,例如:

(case when a.name = 'abc' and b.type = 'X' and c.sign = '+'
      then 1 * (d.amount)
      else 'N/A'
 end)

因为一条路径返回一个数字,所以整个表达式返回一个数字,并且您会遇到类型转换错误。

您需要记住,case表达式返回具有单个类型的单个值。 case中的所有路径应返回相同的类型。在这种情况下,请返回NULL或将数字转换为字符串。

答案 1 :(得分:0)

尝试以下方法:

case when a.name = 'abc' and b.type = 'X' and c.sign = '+'
      then 1 * (d.amount)
      else NULL
 end
相关问题