从SQL Server读取十进制值时发生溢出异常 [英] Overflow exception when reading decimal values from SQL Server

查看:212
本文介绍了从SQL Server读取十进制值时发生溢出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道这是一个错误还是我出了什么问题。

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

我正在使用 SqlDataReader加载值来自SQL Server 2008数据库,但是在某些情况下,它无法将SQL值转换为.net值。 (.NET 4.0)

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:

工作示例:

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

不起作用的例子:

"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检查了SQL Server记录的实际值。它们的区别在于,不工作的人使用4个整数表示值,工作的人仅使用3个整数。

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.

我也使用.net Reflector检查了源代码如果存在的值超过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.

所以,我想知道这是否是真正的.net框架中的错误。

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

推荐答案

除了可能过于精确之外,您所做的并不是错。我不认为这是

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

您可能会认为它是一个错误,或者只是功能上的空白。 .Net 十进制结构只是不能表示存储在SQL Server 十进制中的值,因此<$会引发c $ c> OverflowException 。

You could argue its 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.

您需要在检索值之前对数据库中的兼容值进行操作,或者阅读数据以原始二进制或字符串格式输出,并在.Net端进行操作。

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

这篇关于从SQL Server读取十进制值时发生溢出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆