将varchar(max)转换为decimal时将数据类型varchar转换为numeric时出错

时间:2013-05-03 09:56:37

标签: tsql stored-procedures sql-server-2008-r2 varchar

我正在尝试对两个字符串中的值求和。为了做到这一点,我将字符串转换为小数,添加它们然后将其转换回字符串输出。还使用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

“答案”字段为varchar(max),默认值为“”  问题是我收到错误消息:将数据类型varchar转换为数字

时出错

2 个答案:

答案 0 :(得分:3)

失败的部分是内在案例:

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

CASE表达式(例如上面的)必须只返回一种数据类型。在这种情况下,它不能同时返回小数和varchar(空字符串'')。由于type precedence,任一分支的结果都会转换为小数。如果 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

答案 1 :(得分: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