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

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


当前回答

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.

其他回答

Decimal具有固定精度,而float具有可变精度。

EDIT (failed to read entire question): Float(53) (aka real) is a double-precision (64-bit) floating point number in SQL Server. Regular Float is a single-precision (32-bit) floating point number. Double is a good combination of precision and simplicty for a lot of calculations. You can create a very high precision number with decimal -- up to 136-bit -- but you also have to be careful that you define your precision and scale correctly so that it can contain all your intermediate calculations to the necessary number of digits.

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.

虽然这个问题不包括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')

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

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

参考链接

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

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

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