2017-03-08 111 views
1

有人能解釋這個查詢的行爲:SQL計算輸出精度

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 

我不不同於18明白,爲什麼38分的行爲?

我在想,SQL服務器總是會自動返回一個精確計算結果的精確計算結果?爲了改變這種情況,你必須明確地施加結果?

+0

http://dba.stackexchange.com/a/那些隱式轉換在從你的問題修改的一個例子標記爲'und' 41745/95107,你會注意到,因爲你只使用2精度,使用37的比例將返回與18相同的結果 – scsimon

回答

1

它遵循這裏找到規則:Precision, Scale, and Length (Transact-SQL) - msdn

當使用最大精度,它不能調整尺寸,而不用擔心失去精度。

Chart for Data Type Conversion (Database Engine) - msdn

如果你推出了float到你的計算,你會得到一個float回報。

默認情況下,帶小數的值將隱式轉換爲十進制/數字數據類型。

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