views:

84

answers:

6

I have the following piece of sql query:

Sql += " SELECT     ISNULL(SUM(COALESCE (a.currency, 0)), 0) AS monthCurrency              
FROM          IW_Awards AS a ";

The query works fine, I am trying to cast this value in C# after the query has been submitted and I cannot find what type it is.

I tried int, int? and string. When I tried to cast to a string I had the following error message: Unable to cast object of type 'System.Decimal' to type 'System.String'.

And when I tried to cast it to an Int or Int? I got: Specified cast is not valid.

Database: SQL IDE: Visual Studio 2010 Database interface: LINQ (but I am creating my own query) Server side language: C#

Thank you for your help.

+4  A: 

Did you try decimal? It told you it was trying to cast a System.Decimal to a string when you tried to cast it to a string.

It will return whichever type Currency is.

Mike M.
Thanks it worked!
Lobsterm
+1  A: 

It sounds like it's a decimal. That's what the error message is telling you, you're trying to cast a decimal to a string.

Alex Zylman
+2  A: 

What type is a.currency? I'd say this is probably a decimal datatype from your error message.

Out of curiousity why use coalesce and isnull? Since you have already changed all null values to 0, you shouldn't need the outside isnull at all.

HLGEM
+1 and with no group by so you always get one row too
gbn
If there are no rows in the table, you will still get a NULL even with the inner COALESCE.
Tom H.
a.currency is decimal(4, 0) in Sql, it fixed my problem to know that, thanks :)
Lobsterm
@Tom H. I suppose that is true but personally I'm not in the habit of querying tables that have no records. In that case you should be consistent and use coalesce twice or isnull twice.
HLGEM
@gbn: Umm, his code doesn't include a GROUP BY. So, you will get one NULL row. My comment was in response to HLGEM. Had I been replying to your comment then I would have said so. I'm sorry if that wasn't clear.
Tom H.
@Tom H: er, my mistake. sorry. memo to me: read *and understand* before posting
gbn
+1  A: 

If currency is an int in the database, then use Convert.ToInt32. Another option is to use myTable.Rows[0].Field<int>("monthCurrency") from the System.Data namespace. The problem is sometimes even though you return an int from SqlServer, .NET still thinks it's a decimal.

Yuriy Faktorovich
+1  A: 

It appears to me that the result is a decimal, based on the error message that specifies that it cannot convert from System.Decimal.

David Williams
+1  A: 

As others mentioned, it is decimal that you are looking for, but I want to add this link to the CLR-SQL type mapping documentation (very useful link).

BioBuckyBall
wow thanks for the bible, I wish I had it a few hours back.
Lobsterm