Chuck
Chuck

Reputation: 1210

Overflow exception when reading decimal values from SQL Server

I'm wondering whether this is a bug or if I'm going something wrong.

I'm loading values with a SqlDataReader from a SQL Server 2008 database but under certain circumstances, it fails to convert the SQL values into .net values. (.NET 4.0)

I have traced it down to an test-case which demonstrates the actual problem:

Working example:

"select convert(decimal(38, 19), 260000 ) as test"
rs.GetValue(1);
--> returns 260000 (decimal)

Not working exmaple:

"select convert(decimal(36, 26), 260000 ) as test"

rs.GetValue(1);
--> throws
   System.OverflowException: Conversion overflows.
   at System.Data.SqlClient.SqlBuffer.get_Decimal()
   at System.Data.SqlClient.SqlBuffer.get_Value()
   at System.Data.SqlClient.SqlDataReader.GetValueInternal(Int32 i)
   at System.Data.SqlClient.SqlDataReader.GetValues(Object[] values)

I have examined the actual values that the SQL Server retured. They differ that the non-working one uses 4 integers to express the value, the working one only 3.

I did also check the source code with .net Reflector which unveiled that an exception is thrown if the value exists of more then 3 values, but I dont understand the mechanics behind them.

So, I'm wondering whether this is a genuine bug in the .net framework.

Upvotes: 21

Views: 31988

Answers (1)

Jodrell
Jodrell

Reputation: 35716

It's not something you are doing wrong, apart from being overly precise perhaps. I don't think its a new problem either.

You could argue it's a bug or just a gap in functionality. The .Net Decimal structure just can't represent the value that is stored in your SQL Server decimal so an OverflowException is thrown.

Either you need to manipulate the value to something compatible in the database before you retrieve it or, read the data out in a raw binary or string format and manipulate it on the .Net side.

Alternatively, you could write a new type that handles it.

It's probably simpler just to use a compatible decimal definition in the first place unless you really need that precision. If you do I'd be interested to know why.

Upvotes: 15

Related Questions