【问题标题】:Postgres Alter Column Integer to BooleanPostgres 将列整数更改为布尔值
【发布时间】:2010-12-16 22:52:33
【问题描述】:

我有一个 INTEGER NOT NULL DEFAULT 0 字段,我需要将其更改为 bool。

这是我正在使用的:

ALTER TABLE mytabe 
ALTER mycolumn TYPE bool 
USING 
    CASE 
        WHEN 0 THEN FALSE 
        ELSE TRUE 
    END;

但我得到了:

ERROR:  argument of CASE/WHEN must be type boolean, not type integer

********** Error **********

ERROR: argument of CASE/WHEN must be type boolean, not type integer
SQL state: 42804

有什么想法吗?

谢谢。

【问题讨论】:

    标签: database postgresql


    【解决方案1】:

    试试这个:

    ALTER TABLE mytabe ALTER COLUMN mycolumn DROP DEFAULT;
    ALTER TABLE mytabe ALTER mycolumn TYPE bool USING CASE WHEN mycolumn=0 THEN FALSE ELSE TRUE END;
    ALTER TABLE mytabe ALTER COLUMN mycolumn SET DEFAULT FALSE;
    

    您需要首先删除约束(因为它不是布尔值),其次您的 CASE 语句在语法上是错误的。

    【讨论】:

      【解决方案2】:

      Postgres 可以自动将整数转换为布尔值。关键词是

      using some_col_name::boolean
      -- here some_col_name is the column you want to do type change
      

      上面的答案是正确的,对我有帮助只是一个修改而不是我使用类型转换的案例

      ALTER TABLE mytabe ALTER COLUMN mycolumn DROP DEFAULT;
      ALTER TABLE mytabe ALTER mycolumn TYPE bool USING mycolumn::boolean;
      ALTER TABLE mytabe ALTER COLUMN mycolumn SET DEFAULT FALSE;
      

      【讨论】:

      • 接受的答案更好,因为它依赖于类型转换。例如,此方法以 cannot cast type smallint to boolean 失败。
      • @BenJohnson 试试USING mycolumn::text::boolean;
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-19
      • 2016-04-08
      • 1970-01-01
      • 2016-05-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多