Invalid cast exception when reading result from SQLDataReader

前端 未结 4 876
轻奢々
轻奢々 2021-02-19 05:31

My stored procedure:

    @UserName nvarchar(64),

    AS

    BEGIN
    SELECT MPU.UserName, SUM(TS.Monday)as Monday //TS.Monday contains float value
    FROM db         


        
相关标签:
4条回答
  • 2021-02-19 05:50

    I also had a similar issue and ended up doing this:

    if (!oDR.IsDBNull(0))
        Rating = (float)oDR.GetSqlDecimal(0).Value;
    

    oDR.GetFloat(0) was returning and invalid cast exception when accessing the result of a SELECT AVG(...).

    HTH

    0 讨论(0)
  • 2021-02-19 06:00
    float monday = Convert.ToDouble(reader["Monday"]);
    

    would be a nice approach. I am trying to find a solution for over an hour and it fails here. now it works fine.

    0 讨论(0)
  • 2021-02-19 06:07

    My guess is that the value is being returned as a boxed double instead of float. When you unbox the type has to be exactly right. So assuming I'm right and it's not decimal or something like that, you could use:

    float monday = (float) (double) reader["Monday"];
    

    and it would work. That's pretty ugly though. If you use SqlDataReader.GetFloat it should get it right if it's genuinely a single-precision value, and it's clearer (IMO) what's going on.

    On the other hand, your data could actually be coming back from the database as a double, in which case you should (IMO) use:

    float monday = (float) reader.GetDouble(column);
    

    As an aside, are you sure that float is actually the most appropriate type here in the first place? Often decimal is more appropriate...

    0 讨论(0)
  • 2021-02-19 06:07

    A sql float is a .NET Double, see on the msdn. Try casting to a double.

    0 讨论(0)
提交回复
热议问题