Case语句,将varchar值转换为数据类型int时转换失败

时间:2015-01-06 14:00:36

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

我不知道如何正确解释这一点。在我的详细信息表中,我试图找到费用。让我们说费用都等于10.00美元

我试图做的只是在tranname =' Corr Official'和Fee.Waiver是空的。问题是,表中的字段是varchar。我试图做演员和转换没有成功。

(Case when Detail.FieldValue = '$0.00' and tranname = 'Official' then Fee.Waiver * -1 
when TranName = 'CORR-Official ' and Fee.Waiver IS not null then Fee.Waiver 
when TranName = 'CORR-Official' and Fee.Waiver  IS null then Cast(Detail.FieldValue, int) * -1 
when Detail.FieldValue = '$0.00' and Fee.Waiver IS not null then Fee.Waiver * -1 
when Fee.Waiver IS not null then Fee.Waiver * -1 
when Detail.FieldValue is null and Fee.Waiver IS null then Detail.FieldValue     
else Detail.FieldValue end) as FieldValue

这是我的错误:

Msg 245,Level 16,State 1,Line 1 转换varchar值时转换失败' $ 10.00'数据类型int。

1 个答案:

答案 0 :(得分:4)

您无法将$ 0.00转换为0,因为SQL不是数字。

由于设计似乎无法控制,假设您只有一个美元符号,而不是任何其他货币符号,您可以在转换之前去除美元符号。

在第三行,执行以下操作:

when TranName = 'CORR-Official' and Fee.Waiver  IS null then 
    Cast(Replace(Detail.FieldValue, '$', '') as decimal(18, 2)) * -1

或者,如果您有多种货币(它看起来不像,但是,嘿,让我们彻底):

when TranName = 'CORR-Official' and Fee.Waiver  IS null then 
    Cast(RIGHT(Detail.FieldValue, len(Detail.FieldValue) - 1) as decimal(18, 2)) * -1

但请注意,您还需要转换为小数,而不是整数,否则您将获得:

  

Msg 245,Level 16,State 1,Line 4

     

转换varchar值时转换失败' 0.00&#39>数据类型int。

也就是说,规范化数据并使用适当的数据类型总是一个更好的主意。