Postgres将列整数更改为布尔值

问题描述 投票:40回答:2

我有一个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
2个回答
78
投票

试试这个:

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语句在语法上是错误的。


9
投票

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;
© www.soinside.com 2019 - 2024. All rights reserved.