将数据类型varchar转换为float时出错 - 与ISNULL相关

时间:2012-01-17 14:15:18

标签: sql sql-server-2005 case isnull

注意:我在SO上阅读了类似的线程,但在此查询中没有任何帮助。

我已经复制了以下代码,其中类似于我的实际问题。我必须使用这种语法,因为它已经在数据库中使用过了,除非有一个令人信服的建议,这里的逻辑是错误的。

在我的实际问题中,此查询在大部分时间工作,但在某个时间失败。调查后我发现问题是

ISNULL(amount,0)

这是因为如果任何类别都有值0,0或两个值都为null,null,ISNULL使它们成为一个字符串,因此我得到了

  

将数据类型varchar转换为float

时出错

以下是我带有评论的测试代码

create table #table1 (
id int not null primary key identity,
category varchar(10),
amount float null
)

insert into #table1 values('A',23)
insert into #table1 values('A',23)
insert into #table1 values('B',NULL)
insert into #table1 values('B',0)
insert into #table1 values('C',NULL)
insert into #table1 values('C',NULL)
insert into #table1 values('D',0)
insert into #table1 values('D',0)

select * from #table1 -- works

select category, sum1  -- works
 from 
(select category, SUM(Round(ISNULL(amount,0),0)) as Sum1 from #table1
group by category)  D

select category, sum2 = -- does not work
case Sum1
    when 'A' then Sum1 * 1   -- my problem is here
    when 'B' then Sum1 * 2   -- this is the logic in my actual code
    when 'C' then Sum1 * 3   -- would like to make this query work
    when 'D' then Sum1 * 4
    else Sum1
end 
 from 
(select category, SUM(Round(ISNULL(amount,0),0) ) as Sum1 from #table1
group by category)  D

我做错了什么?

2 个答案:

答案 0 :(得分:3)

不应该是你的案例陈述是"案例类别"而不是"案例sum1"?

如果更改,查询将按预期工作。

答案 1 :(得分:2)

您的案例需要查看类别而不是sum1

select category, sum2 = -- does not work
case category
    when 'A' then Sum1 * 1   -- my problem is here
    when 'B' then Sum1 * 2   -- this is the logic in my actual code
    when 'C' then Sum1 * 3   -- would like to make this query work
    when 'D' then Sum1 * 4
    else Sum1
end 
 from 
(select category, SUM(Round(ISNULL(amount,0),0) ) as Sum1 from #table1
group by category)  D