为什么我的十进制值在 SQL 插入中四舍五入为整数?

Why are my decimal values being rounded to integers in SQL insertions?

我正在使用 SQL Server Management Studio 并具有以下架构:

CREATE TABLE tmp(
    id int NOT NULL IDENTITY(1,1)PRIMARY KEY,
    toleranceRegion DECIMAL
)

然后我执行以下插入:

INSERT INTO tmp VALUES(3.2); 
INSERT INTO tmp VALUES(5.678);
INSERT INTO tmp VALUES(1.95);

预期输出:

id  toleranceRegion
--  ---------------
1   3.2
2   5.678
3   1.95

实际输出:

id  toleranceRegion
--  ---------------
1   3
2   6
3   2

为什么插入的 toleranceRegion 值四舍五入到最接近的整数?

设置你的精度

十进制(18,4)

这将是小数

这是因为你没有设置scale,这意味着系统使用的是默认的零比例:

s (scale) The number of decimal digits that will be stored to the right of the decimal point. This number is subtracted from p to determine the maximum number of digits to the left of the decimal point. The maximum number of decimal digits that can be stored to the right of the decimal point. Scale must be a value from 0 through p. Scale can be specified only if precision is specified. The default scale is 0. (emphasis added)

换句话说,SQL Server stores zero digits to the right of decimal point.

您没有为小数定义 scale/precision。如果您想要小数点后 3 位数字,则应将其定义为 DECIMAL(9,3),这将为您提供小数点前 6 位和最多 3 位小数。 您需要分析预期数据,并根据预期为您的列定义指定正确的精度和小数位数。

CREATE TABLE tmp(
    id int NOT NULL IDENTITY(1,1)PRIMARY KEY,
    toleranceRegion DECIMAL(9,3)
)

请参阅 decimal here 的 Sql 服务器文档。

这里的问题是你是如何定义 DECIMAL 列的精度的?

如果是DECIMAL(10, 2)则一共有11个数,其中2个是小数(2个小数四舍五入就是10.215存为11.22,11.214存为11.21)。

如果它是 DECIMAL(10),它将没有任何小数值并四舍五入为整数。

在你的问题中你定义了 toleranceRegion DECIMAL 所以它四舍五入到下一个整数 如果你声明 table 就像

CREATE TABLE tmp(
id int NOT NULL IDENTITY(1,1)PRIMARY KEY,
toleranceRegion DECIMAL(10,3)

)

那么它不会四舍五入,你会得到你想要的结果

INSERT INTO tmp VALUES(3.2); 
INSERT INTO tmp VALUES(5.678);
INSERT INTO tmp VALUES(1.95);

输出:

id  toleranceRegion
--  ---------------
1   3.2
2   5.678
3   1.95

注意:- 如果您使用 FLOAT 或 DOUBLE PRECISION,则不必指定小数位数,但它有其自身的缺陷。

更多详情您可以click here