最近看書的時候看到這么一句話:
對于聲明了精度的數值,如果insert插入的數值大于聲明的精度范圍,則會報錯。
那么這里的精度范圍是什么?精度代表的數值就是位數嗎?即3是不是意味著最大值就是999?
測試了一堆數據發現如下:
如果精度和標度都沒有聲明,那么插入的數值將保持原樣,沒有范圍約束。(當然不可以超出系統內可以實現的精度和標度)。
testdb=# create table numeric(n1numeric(3,0),n2 numeric(3,0),n3 numeric(3,2),n4 numeric);
CREATE TABLE
testdb=# insert into numericvalues(3.1,3.5,3.12,3.123);
INSERT 0 1
testdb=# select * from numeric;
n1 |n2 | n3 | n4
----+----+------+-------
3| 4 | 3.12 | 3.123
(1 row)
可以發現,超出標度的數值確實是按照四舍五入的方式插入的。
testdb=# insert into numeric values(999.4999,5,9.991,13.123);
INSERT 0 1
testdb=# insert into numericvalues(999.5,5,9.994,13.123);
ERROR: numeric field overflow
DETAIL: A field with PRecision 3, scale 0 must round to an absolute value lessthan 10^3.
STATEMENT: insert into numeric values(999.5,5,9.994,13.123);
ERROR: numeric field overflow
DETAIL: A field with precision 3, scale 0 must round to an absolute value lessthan 10^3.
這兩組數據就意味著numeric(3,0)所能插入的最大值為999.4999(9循環),即總是小于999.5。
這個時候我想,那numeric(3,2)是不是就意味著必須小于999.49呢?繼續插入數值,找到了臨界值:
testdb=# insert into numericvalues(999.4999,5,9.994999999999999999,13.123);
INSERT 0 1
testdb=# insert into numericvalues(1,2,9.995,22.123);
ERROR: numeric field overflow
DETAIL: A field with precision 3, scale 2 must round to an absolute value lessthan 10^1.
STATEMENT: insert into numeric values(1,2,9.995,22.123);
ERROR: numeric field overflow
DETAIL: A field with precision 3, scale 2 must round to an absolute value lessthan 10^1.
這兩組數據證明了numeric(3,2)最大值是9.99499999(9循環),即總是小于9.995。這也就是說明所謂的精度范圍是要和標度結合的一個范圍,精度值表示的位數是要把標度(小數點后幾位)算進去的。
而沒有精度和標度的數值范圍(系統所能承受的精度范圍)我并沒有測試出來,這個意義不大。
testdb=# insert into numeric
values(999.4999999,999.49999999999,9.99499999999999999,99999999999999.99999999);
INSERT 0 1
testdb=# select * from numeric;
n1 |n2 | n3 | n4
-----+-----+------+-------------------------
3| 4 | 3.12 | 3.123
5| 4 | 3.12 | 3.123
5| 4 | 5.12 | 3.123
13| 4 | 5.12 | 3.123
13| 4 | 8.12 | 13.123
999| 4 | 9.12 | 13.123
999| 5 | 9.99 | 13.123
999| 5 | 9.99 | 13.123
999| 5 | 9.99 | 13.123
999| 5 | 9.99 | 13.123
999| 999 | 9.99 | 99999999999999.99999999
(11 rows)
新聞熱點
疑難解答