简体   繁体   English

使用十进制值更新 SQL 表只会产生 0

[英]Updating SQL table with decimal values yields only 0s

On MSSQL: I am adding a column to a table在 MSSQL 上:我正在向表中添加一列

ALTER table
ADD x_column DECIMAL

Now, I perform a calculation using another column of the same table:现在,我使用同一张表的另一列执行计算:

SELECT SELECT CAST(a_column AS decimal)/CAST (1000000000*0.1*12 AS decimal) FROM table

This yields the expected result:这产生了预期的结果:

+---+-----------------------+
¦ 1 ¦ 0.0000732950000000000 ¦
+---+-----------------------+
¦ 2 ¦ 0.0000016912500000000 ¦
+---+-----------------------+
¦ 3 ¦ 0.0005905541666666666 ¦
+---+-----------------------+                  

However, when I try to update the table with these values, all I get are zeroes:但是,当我尝试使用这些值更新表时,我得到的都是零:

UPDATE table
SET x_column = CAST(a_column AS DECIMAL)/CAST(1000000000*0.1*12 AS decimal)

 id   x_column
+---+-----------------------+
¦ 1 ¦ 0                     ¦
+---+-----------------------+
¦ 2 ¦ 0                     ¦
+---+-----------------------+
¦ 3 ¦ 0                     ¦
+---+-----------------------+ 

What I'd like is for the results of the above SELECT to be inserted into the column in the table.我想要将上述 SELECT 的结果插入表中的列中。

You forgot to add the precision and scale on the DECIMAL datatype .您忘记在DECIMAL数据类型上添加精度和小数位数。

If not specified, the default scale is 0.如果未指定,则默认比例为 0。

When you add your column you should use:添加列时,您应该使用:

ALTER table
ADD x_column DECIMAL(35, 19)

or something larger up to 38 digits.或更大的东西,最多 38 位。

Precision is how many digits your number would have, while the scale is the number of digits after the decimal point.精度是您的数字的位数,而比例是小数点的位数。

You should add scale and precision to your columne declaration, if omitted it is 0您应该在您的 columne 声明中添加比例和精度,如果省略,则为 0

ALTER table ADD x_column DECIMAL(28,12)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM