SQL计算输出精度

时间:2017-03-08 17:35:30

标签: sql-server precision decimal-precision

有人可以解释此查询的行为:

SELECT
    0.1 + 0.01,
    '',
    (CAST(0.1 AS numeric(18,1)))+(CAST(0.01 AS numeric (18,2))),
    0.1 + (CAST(0.01 AS numeric (18,2))),
    (CAST(0.1 AS numeric(18,1)))+ 0.01,
    '',
    (CAST(0.1 AS numeric(38,1)))+(CAST(0.01 AS numeric (38,2))),
    0.1 + (CAST(0.01 AS numeric (38,2))),
    (CAST(0.1 AS numeric(38,1)))+ 0.01

我不明白为什么38的表现与18?

不同

我原以为SQL服务器总是会以精确显示结果所需的精度自动返回计算结果?要改变这一点,你必须明确地转换结果吗?

1 个答案:

答案 0 :(得分:1)

遵循此处的规则:Precision, Scale, and Length (Transact-SQL) - msdn

当您使用最大精度时,它无法调整比例而不会有丢失精度的风险。

Chart for Data Type Conversion (Database Engine) - msdn

如果您在计算中引入float,则会获得float次返回。

默认情况下,带小数的值将隐式转换为decimal / numeric数据类型。在根据您的问题修改的示例中,这些隐式转化标记为'und'

select
      undefined=0.1 + 0.01
    ,[18,1+18,2] = (cast(0.1 as numeric(18,1)))+(cast(0.01 as numeric (18,2)))
    ,[und+18,2+18,1] = 0.1 + (cast(0.01 as numeric (18,2)))
    ,[18,2+und]=(cast(0.1 as numeric(18,1)))+ 0.01
    ,[38,1+38,2]=(cast(0.1 as numeric(38,1)))+(cast(0.01 as numeric (38,2)))
    ,[und+38,2] = 0.1 + (cast(0.01 as numeric (38,2)))
    ,[38,1+und]=(cast(0.1 as numeric(38,1)))+ 0.01
    ,[38,1+float]=(cast(0.1 as numeric(38,1)))+ convert(float,0.01)

rextester演示:http://rextester.com/ULVRGS77309

返回:

+-----------+-----------+---------------+----------+-----------+----------+----------+------------+
| undefined | 18,1+18,2 | und+18,2+18,1 | 18,2+und | 38,1+38,2 | und+38,2 | 38,1+und | 38,1+float |
+-----------+-----------+---------------+----------+-----------+----------+----------+------------+
| 0,11      | 0,11      | 0,11          | 0,11     | 0,1       | 0,11     | 0,1      | 0,11       |
+-----------+-----------+---------------+----------+-----------+----------+----------+------------+