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

为什么我不能在Postgres中修改列类型

  •  0
  • ddd  · 技术社区  · 7 年前

    我正在尝试将列的类型从varchar更改为integer。当我运行以下命令时

    alter table audio_session
    alter column module_type_cd type INT USING module_type_cd::integer,
    alter column sound_type_cd type INT USING sound_type_cd::integer
    

    我搞错了:

    ERROR:  invalid input syntax for integer: "string"
    SQL state: 22P02
    

    这个错误没有任何意义。命令中根本没有“字符串”。我做错了什么?

    2 回复  |  直到 7 年前
        1
  •  2
  •   Barbaros Özhan    7 年前

    栏目 audio_session.module_type_cd audio_session.sound_type_cd 至少有一个 非数值的 在每行的所有值中的值。所以,它是 不可能的 完全转变为 数字的 数据类型。

    例如:

    create table Table1( col1 varchar(10), col2 varchar(10) );
    insert into Table1 values('1','1');
    insert into Table1 values('2','2');
    insert into Table1 values('3','C3');
    
    select CAST(coalesce(col1, '0') AS integer) as converted from Table1; -- this works
    select CAST(coalesce(col2, '0') AS integer) as converted from Table1; -- but, this doesn't
    

    SQL Fiddle Demo

        2
  •  2
  •   klin    7 年前

    命令中根本没有“字符串”。

    但一定在数据里。要使用的命令尝试将所有列的值强制转换为整数。检查一下:

    select *
    from audio_session
    where module_type_cd = 'string' or sound_type_cd = 'string';