0

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.

6 Answers 6

5

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.

0
2

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.

5
  • 3
    If there are no rows in the table, you will still get a NULL even with the inner COALESCE.
    – Tom H
    Aug 11, 2010 at 17:16
  • a.currency is decimal(4, 0) in Sql, it fixed my problem to know that, thanks :) Aug 11, 2010 at 17:20
  • 1
    @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
    Aug 11, 2010 at 17:34
  • @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
    Aug 11, 2010 at 19:45
  • @Tom H: er, my mistake. sorry. memo to me: read and understand before posting
    – gbn
    Aug 11, 2010 at 19:59
1

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.

1

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

1

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).

0
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.