代码之家  ›  专栏  ›  技术社区  ›  gene

在SQL中将int除以100时,得到0而不是decimal

  •  0
  • gene  · 技术社区  · 4 年前

    我有一个专栏Column1 int 键入 myTable 假设值为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

    我做错了什么?

    2 回复  |  直到 4 年前
        1
  •  0
  •   Gordon Linoff    4 年前

    我建议:

    select Column1 / 100.0
    

    SQL Server执行整数除法(如您所发现的)。只需在常数中包含一个小数位或乘以 1.0 通常可以解决问题。

        2
  •  0
  •   SteveC    4 年前

    尝试

    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