简体   繁体   English

从SQL Server读取十进制值时出现溢出异常

[英]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. 我正在使用SQL Server 2008数据库中的SqlDataReader加载值,但在某些情况下,它无法将SQL值转换为.net值。 (.NET 4.0) (.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. 我已经检查了SQL Server恢复的实际值。 They differ that the non-working one uses 4 integers to express the value, the working one only 3. 他们的不同之处在于,非工作人员使用4个整数来表示价值,而工作人员只使用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 Reflector的源代码,它揭示了如果值存在超过3个值时抛出异常,但我不理解它们背后的机制。

So, I'm wondering whether this is a genuine bug in the .net framework. 所以,我想知道这是否是.net框架中的真正错误。

Its not somthing you are doing wrong, apart from being overly precise perhaps. 除了过于精确之外,这不是你做错的事。 I don't think its a new problem either . 我也不认为这是一个新问题

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 Decimal结构不能表示存储在SQL Server decimal的值,因此抛出了OverflowException

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. 您需要在检索之前将值操作到数据库中的兼容内容,或者以原始二进制或字符串格式读取数据并在.Net端进行操作。

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. 除非你真的需要那种精度,否则首先使用兼容的decimal定义可能更简单。 If you do I'd be interested to know why. 如果你这样做,我有兴趣知道为什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM