如何在 SQL 服务器中将 VARCHAR 列转换为 DECIMAL 而无需四舍五入?

How to convert VARCHAR columns to DECIMAL without rounding in SQL Server?

在我的 SQL class 中,我正在使用一个 table,这就是全部 VARCHAR。我正在尝试将每一列转换为更正确的数据类型。

例如。我有一个名为 Item_Cost 的列,其值如下:

1.25000000000000000000

我尝试运行这个查询:

ALTER TABLE <table> 
    ALTER COLUMN Item_Cost DECIMAL

此查询 运行 成功,但将其变为 1 而不是 1.25。

如何防止舍入?

查看 the documentation 数据类型 decimal。类型由可选参数 p (precision)s (scale) 定义。后者确定小数点右边的数字。

文档摘录(我用粗体突出显示了重要的部分):

s (scale)

The number of decimal digits that are 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. Scale must be a value from 0 through p, and can only be specified if precision is specified. The default scale is 0 and so 0 <= s <= p. Maximum storage sizes vary, based on the precision.

定义合适的精度和比例可以解决您的问题。

示例数据

create table MyData
(
  Item_Cost nvarchar(100)
);

insert into MyData (Item_Cost) values ('1.25000000000000000000');

解决方案

ALTER TABLE MyData Alter Column Item_Cost DECIMAL(10, 3);

结果

Item_Cost
---------
1.250

Fiddle