System.Data.SqlClient.SqlException: Error converting data type varchar to float.

If you are getting the above .NET error, one reason for this is wrong case statement. Here is an example


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 — Error converting data type varchar to float
when ‘B’ then Sum1 * 2
when ‘C’ then Sum1 * 3
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

 

I get System.Data.SqlClient.SqlException: Error converting data type varchar to float. for this from my C# code when i access the “does not work” query. You can see there is a problem here, the CASE statement is wronglyl written. The correct statement should be


select category, sum2 = -- does not work
case Category -- Fixed the stetement here
when 'A' then Sum1 * 1 -- no error
when 'B' then Sum1 * 2
when 'C' then Sum1 * 3
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

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s