“Specified cast is not valid” when populating DataTable from OracleDataAdapter.Fill()

后端 未结 3 759
生来不讨喜
生来不讨喜 2021-02-02 11:36

I can\'t seem to find this question anywhere on Google (or StackOverflow), which really surprised me, so I\'m putting it on here to help others in the same situation.

I

相关标签:
3条回答
  • 2021-02-02 11:39

    Answering my own question:

    So it seems that the Oracle number type can hold many more decimal places than the C# decimal type and if Oracle is trying to return more than C# can hold, it throws the InvalidCastException.

    Solution?

    In your sql, round any results that might have too many decimal places to something sensible. So I did this:

    SELECT acct_no, ROUND(market_value/mv_total, 8)  -- rounding this division solves the problem
    FROM myTable
    WHERE NVL(market_value, 0) != 0
    AND NVL(mv_total, 0) != 0
    

    And it worked.

    The take away is: Incompatibility between Oracle number type and C# decimal. Restrict your Oracle decimal places to avoid the invalid cast exceptions.

    Hope this helps someone else!

    0 讨论(0)
  • 2021-02-02 11:50

    I know this has been answered already, but I also found another alternative that I use as well. I used a CAST on the field that was giving me troubles.

    Based on OP's SELECT command:

    SELECT acct_no, CAST((market_value/mv_total) AS DECIMAL(14,4))  -- CAST to decimal here
    FROM myTable
    WHERE NVL(market_value, 0) != 0
    AND NVL(mv_total, 0) != 0
    
    0 讨论(0)
  • 2021-02-02 11:59

    I know this thread is really old.. However I had a similar issue.

    The best solution I have to use the Oracle method TO_BINARY_DOUBLE on Oracle Decimal column

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