【问题标题】:Getting 0 instead of decimal when dividing a int by 100 in SQL在 SQL 中将 int 除以 100 时得到 0 而不是小数
【发布时间】:2021-01-01 12:24:32
【问题描述】:

我在myTable 中有一个int 类型的列Column1,其值为25。

cast(Column1 as decimal)/100 插入到临时表#tempTbl 中时,如下所示

create table #tempTbl
(
   Column1 decimal
)

Insert into #tempTbl
select cast(Column1 as decimal)/100
from myTable

我在临时表的 Column1 中看到 0 而不是 0.25

当我尝试select cast(25 as decimal)/100 时,我得到 0.25

我做错了什么?

【问题讨论】:

  • 用您正在使用的数据库标记您的问题。
  • 目标表的数据类型是什么? decimal 没有精确度,您的 DBMS 可能默认没有小数位,即 decimal(??,0)
  • 目标临时表的数据类型为十进制。我将其更改为十进制(6,3)并且它有效
  • decimal 不是数据类型,它需要 precision 和 scale,例如在 SQL Server 中,默认精度为 18,默认小数位数 0

标签: sql casting


【解决方案1】:

我建议:

select Column1 / 100.0

SQL Server 进行整数除法(如您所见)。只需在常量中包含小数位或乘以 1.0 通常可以解决问题。

【讨论】:

  • @gene 。 . .你指的是查询吗?或者您将一个值插入到具有decimal 列且没有定义比例的表中?
  • 使用查询并从查询中插入值时
  • @gene 。 . .您的列的定义不允许小数位。你需要正确定义它。
【解决方案2】:

试试

select cast(Column1 as decimal)/100.0

如果执行

select 25/100.0;

返回

(No column name)
0.250000

请查看此代码。十进制长度在临时表的 DDL 中指定

create table #tempTbl
(
   Column1 decimal(8,2)
)

Insert into #tempTbl
select 25

select Column1/100.0 from #tempTbl;

输出

0.2500000

【讨论】:

  • 这正是我将 25 除以 100 时得到的结果。但是,当我使用列名时,我得到 0 (Column1/100.0)
  • 更新了 column1 为十进制 (8,2) 的示例
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 2014-05-29
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
相关资源
最近更新 更多