【问题标题】:Reduce decimal data type precision & scale and avoid arithmetic overflow error降低十进制数据类型精度和比例,避免算术溢出错误
【发布时间】:2013-04-09 01:18:30
【问题描述】:

我在 SQL Server 2012 数据库中有一个当前为十进制 (30,20) 的字段,因为这是数据提供程序的格式。然而,这么大的小数是完全没有必要的,考虑到这个表有数百万行,我想把它修剪成小数(16,7)。

我尝试了以下 SQL:

alter table mytable alter column mycolumn decimal(16,7)

但这导致了错误:

Arithmetic overflow error converting numeric to data type numeric.

更改此字段的最佳方法是什么?我显然意识到错误正在发生,因为列中的值超过了新的精度。我想知道的是,是否有一个脚本可以截掉小数点后7位的任何数字,然后转换列数据类型?

【问题讨论】:

    标签: sql sql-server sql-server-2012 alter-table alter-column


    【解决方案1】:

    减少到小数点后 7 位:

    update mytable set newcolumn = convert(decimal(16, 7), mycolumn);
    
    update mytable set mycolumn = null;
    
    commit;
    
    alter table mytable alter column mycolumn decimal(16,7)
    
    update mytable set mycolumn = newcolumn;
    
    commit;
    
    alter table mytable drop column newcolumn;
    

    【讨论】:

    • 尝试了这个解决方案...它使所有值的格式为:###.#######00000000000000000000。当我重新运行 alter column 脚本时,仍然出现同样的错误。
    • 改用convert。您可能还需要为转换创建一个临时列(请参阅更新的答案)。
    猜你喜欢
    • 2015-11-22
    • 1970-01-01
    • 2021-08-13
    • 1970-01-01
    • 2012-02-19
    • 1970-01-01
    • 2010-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多