2

我正在尝试对两个字符串的值求和。为了做到这一点,我将字符串转换为小数,将它们相加,然后将其转换回字符串以用于输出。还使用 max 来避免重复条目。我的 SP 中有以下行:

Cast( Max(CASE WHEN QuestionID = 261 THEN CAST(Answer AS decimal) ELSE '' END) + Max(CASE WHEN QuestionID = 260 THEN CAST(Answer AS decimal) ELSE '' END) AS varchar) as Total

Answer 字段为 varchar(max),默认值为 ''。
问题是我收到错误消息:将数据类型 varchar 转换为数字时出错

4

2 回答 2

3

失败的部分是内壳:

CASE WHEN QuestionID = 261
     THEN CAST(Answer AS decimal)
     ELSE '' END

一个CASE表达式(egabove)必须只返回一种数据类型。在这种情况下,它不能同时返回小数和 varchar(空字符串 '')。由于类型优先,来自任一分支的结果都被转换为小数。如果ANY行有QuestionID != 261,它将尝试将其''转换为十进制,并且bam - 你的错误。

你需要这个:

Cast( Max(CASE WHEN QuestionID IN (261,260) AND ISNUMERIC(ANSWER) = 1
               THEN CAST(Answer AS decimal)
               ELSE 0 END)
   AS varchar) as Total
于 2013-05-03T10:05:46.977 回答
0

这有点可读性..

Cast(Max(CASE WHEN QuestionID = 261 THEN CAST(Case When Answer = '' Then 0 Else CAST(Answer as decimal(9,2)) End as decimal(9,2))End ) + Max(CASE WHEN QuestionID = 260 THEN CAST(Case When Answer = '' Then 0 Else CAST(Answer as decimal(9,2)) End as decimal(9,2))End )AS varchar(Max)) as Total

于 2013-05-03T10:19:38.047 回答