问题描述
我有一个整数而不是null默认为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
有什么想法吗?
谢谢.
推荐答案
尝试以下方法:
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语句在语法上是错误的.
其他推荐答案
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;
其他推荐答案
还检查您的列上没有任何检查约束:
[...] CONSTRAINT blabla CHECK ((field = ANY (ARRAY[0, 1])))
否则,您将使用cannot convert to boolean type
alter命令错误问题描述
I've a field that is INTEGER NOT NULL DEFAULT 0 and I need to change that to bool.
This is what I am using:
ALTER TABLE mytabe ALTER mycolumn TYPE bool USING CASE WHEN 0 THEN FALSE ELSE TRUE END;
But I am getting:
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
Any idea?
Thanks.
推荐答案
Try this:
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;
You need to remove the constraint first (as its not a boolean), and secondly your CASE statement was syntactically wrong.
其他推荐答案
Postgres can automatically cast integer to boolean. The key phrase is
using some_col_name::boolean -- here some_col_name is the column you want to do type change
Above Answer is correct that helped me Just one modification instead of case I used type casting
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;
其他推荐答案
Also check that you don't have any CHECK constraint on you column like:
[...] CONSTRAINT blabla CHECK ((field = ANY (ARRAY[0, 1])))
otherwise you alter command will error with a cannot convert to boolean type