数字、浮点和十进制数据类型之间的区别是什么?在哪些情况下应该使用哪种数据类型?

对于任何类型的财务交易(例如工资领域),哪一个是首选的,为什么?


当前回答

虽然这个问题不包括MONEY数据类型,但有些人可能会想使用MONEY数据类型进行财务计算。

注意MONEY数据类型,它的精度有限。

在这个Stackoverflow问题的答案中有很多关于它的好信息:

在SQL Server中应该选择MONEY还是DECIMAL(x,y)数据类型?

其他回答

它们的数据类型优先级不同

Decimal和Numeric在功能上是相同的,但仍然有数据类型优先级,这在某些情况下可能是至关重要的。

SELECT SQL_VARIANT_PROPERTY(CAST(1 AS NUMERIC) + CAST(1 AS DECIMAL),'basetype')

结果数据类型是数值型,因为它具有数据类型优先级。

按优先级列出的详尽数据类型列表:

参考链接

MSDN指南:使用十进制、浮点和真实数据

The default maximum precision of numeric and decimal data types is 38. In Transact-SQL, numeric is functionally equivalent to the decimal data type. Use the decimal data type to store numbers with decimals when the data values must be stored exactly as specified. The behavior of float and real follows the IEEE 754 specification on approximate numeric data types. Because of the approximate nature of the float and real data types, do not use these data types when exact numeric behavior is required, such as in financial applications, in operations involving rounding, or in equality checks. Instead, use the integer, decimal, money, or smallmoney data types. Avoid using float or real columns in WHERE clause search conditions, especially the = and <> operators. It is best to limit float and real columns to > or < comparisons.

仅当十进制(最多38位)提供的精度不够时,才使用float或real数据类型

近似数值数据类型(见表3.3)不存储为许多数字指定的确切值;它们存储的值非常接近。(技术) 避免在WHERE子句搜索条件中使用浮点或实列,特别是=和<>操作符。最好将浮动列和实列限制为>或<比较。(技术)

所以通常选择Decimal作为数据类型是最好的选择

你的号码可以放进去。十进制精度为10E38[~ 38位数字] 较小的存储空间(可能是计算速度)对你来说并不重要 需要精确的数值行为,例如在金融应用程序中,在涉及舍入的操作中,或在相等检查中。(技术)


精确数值数据类型十进制和数字- MSDN

Numeric =十进制(5到17字节) 将映射到。net中的Decimal 在SQL server中,两者都有(18,0)作为默认的(precision,scale)参数 刻度=可以存储在小数点右侧的最大小数位数。 money(8字节)和smallmoney(4字节)也是精确数据类型,将映射到。net中的Decimal,并有4个小数点(MSDN)。

近似数值数据类型浮动和实- MSDN

实(4字节) 在。net中将映射为Single real的ISO同义词是float(24) 浮点数(8字节) 在。net中将映射到Double

All exact numeric types always produce the same result, regardless of which kind of processor architecture is being used or the magnitude of the numbers The parameter supplied to the float data type defines the number of bits that are used to store the mantissa of the floating point number. Approximate Numeric Data Type usually uses less storage and have better speed (up to 20x) and you should also consider when they got converted in .NET What is the difference between Decimal, Float and Double in C# Decimal vs Double Speed SQL Server - .NET Data Type Mappings (From MSDN)

主要来源:MCTS自定速度训练包(考试70-433):Microsoft®SQL Server®2008数据库开发-第3章-表,数据类型和声明性数据完整性第1课-选择数据类型(指南)-第93页

不是一个完整的答案,但一个有用的链接:

“我经常用十进制数值来计算。在某些情况下,在进行任何计算之前立即将十进制值转换为浮点值,可以获得更好的精度。”

http://sqlblog.com/blogs/alexander_kuznetsov/archive/2008/12/20/for-better-precision-cast-decimals-before-calculations.aspx

虽然这个问题不包括MONEY数据类型,但有些人可能会想使用MONEY数据类型进行财务计算。

注意MONEY数据类型,它的精度有限。

在这个Stackoverflow问题的答案中有很多关于它的好信息:

在SQL Server中应该选择MONEY还是DECIMAL(x,y)数据类型?