【问题标题】:Avoid error out of range SQL during database migration避免在数据库迁移过程中出现错误超出范围的 SQL
【发布时间】:2021-02-16 11:05:26
【问题描述】:

我在我的 SQL 表中遇到迁移问题,

例如,我有一个名为 Error 的表,其中包含值

latitude DECIMAL(9,2)
longitude DECIMAL(10,8)
info DECIMAL(11,8)
idsf int
sf tinyint
value float

这些行必须更改为:

latitude DECIMAL(9,2) => DECIMAL(7,1)
longitude DECIMAL(10,8) => DECIMAL(8,6)
info DECIMAL(11,8) => DECIMAL(9,6)
idsf int => DECIMAL(7,2)
sf tinyint => DECIMAL(5,2)
value float => DECIMAL(7,1)

问题是我每次都遇到超出范围的问题,因为某些值不会自动截断。

这可能有解决方法吗?

感谢您的宝贵时间

【问题讨论】:

    标签: mysql sql sql-types


    【解决方案1】:

    您可以更新数据以将值设置为范围内的类型。这看起来像:

    update t
        set latitude = (case when latitude between -999999.9 and 999999.9
                             then latitude
                        end),
            longitude = (case when longitude between -99.999999 and 99.999999
                              then longitude
                         end),
            . . . 
    

    不过,我建议您先调查这些值,以确定不正确的值是什么样的 - 以及如何处理它们。

    即使在这一点上,数据看起来也很可疑:

    • latitudelongitude 通常具有相同的数据类型。
    • longitudes 从 -180 到 180 不等——假设它们以度为单位。
    • latitudeslogitudes 通常会有 4 或 6 个小数点,所以我希望像 decimal(9, 6) 或类似的东西。

    毫无疑问,可能还有其他问题。

    【讨论】:

    • 感谢您的回答,问题是由于超过 300 万行,我什至不知道所有纬度和经度内到底是什么......我真的不明白代码的含义例如,这是为了将所有纬度值转换为 -999999.9 到 99999.9 中包含的内容吗?
    • @xFGerald 。 . .不会。这会将超出该范围的值替换为 NULL,因此您不会收到转换错误。
    • 所以我会失去价值?
    • @xFGerald 。 . .答案专门为此提供了警告。如果要更改数据类型,您需要弄清楚如何处理超出范围的值。
    猜你喜欢
    • 2013-01-25
    • 2018-06-18
    • 2023-03-09
    • 2016-11-14
    • 1970-01-01
    • 2017-05-22
    • 1970-01-01
    • 2021-11-20
    • 2023-04-07
    相关资源
    最近更新 更多