Postgres将列整数更改为布尔值

sam*_*ina 42 database postgresql

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

这就是我正在使用的:

ALTER TABLE mytabe 
ALTER mycolumn TYPE bool 
USING 
    CASE 
        WHEN 0 THEN FALSE 
        ELSE TRUE 
    END;
Run Code Online (Sandbox Code Playgroud)

但我得到:

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
Run Code Online (Sandbox Code Playgroud)

任何的想法?

谢谢.

cat*_*ave 81

试试这个:

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;
Run Code Online (Sandbox Code Playgroud)

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


小智 10

上面的答案是正确的,帮助我只是一个修改,而不是我使用类型铸造的情况

using some_col_name::boolean
-- here some_col_name is the column you want to do type change
Run Code Online (Sandbox Code Playgroud)

  • @BenJohnson 尝试`使用 mycolumn::text::boolean;` (2认同)