Error converting data type varchar to float - ISNULL related
-
29-10-2019 - |
Question
Note: I read similar threads on SO but was of no help in this query.
I have reproduced the following code where is similar to my real problem. I have to use this syntax because it is already been used in the database, unless there is a convincing advice, the logic is wrong here.
In my actual problem, this query works most of the time but fails on a certain time. After investigating I found that the problem is
ISNULL(amount,0)
This is because if any category has both values 0,0 or both values null, null, ISNULL
makes them a string and therefore I get
Error converting data type varchar to float
The following is my test code with comments
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
What am I doing wrong?
Solution
Shouldn't your case statement be "case category" and not "case sum1"?
If you change that, the query works as expected.
OTHER TIPS
your case needs to look at category not 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