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

Case Statement, conversion failed when converting varchar value to data type int

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

我想做的只是在 tranname = 'Corr Official' 且 Fee.Waiver 为 Null 时使字段值为负。问题是,table 中的字段是 varchar。我曾尝试进行演员表和转换,但没有成功。

(Case when Detail.FieldValue = '[==].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 = '[==].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

这是我的错误:

消息 245,级别 16,状态 1,第 1 行 将 varchar 值“$10.00”转换为数据类型 int 时转换失败。

您不能将 $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

Conversion failed when converting the varchar value '0.00' to data type int.

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