向现有的ENUM类型添加新值

12 浏览
0 Comments

向现有的ENUM类型添加新值

我有一个使用 enum 类型的表列。我希望更新该 enum 类型以包含一个额外的可能值。我不想删除任何现有值,只是添加新的值。最简单的方法是什么?

admin 更改状态以发布 2023年5月24日
0
0 Comments

注意:如果您使用的是PostgreSQL 9.1或更高版本,并且您不介意在事务外进行更改,请参见此回答以获取更简单的方法。


我在几天前遇到了同样的问题,并找到了这篇文章。因此我的回答可能对正在寻找解决方案的人有所帮助 🙂

如果您只有一个或两个使用枚举类型的列需要更改,可以尝试这种方法。同时,您也可以更改新类型中值的顺序。

-- 1. rename the enum type you want to change
alter type some_enum_type rename to _some_enum_type;
-- 2. create new type
create type some_enum_type as enum ('old', 'values', 'and', 'new', 'ones');
-- 3. rename column(s) which uses our enum type
alter table some_table rename column some_column to _some_column;
-- 4. add new column of new type
alter table some_table add some_column some_enum_type not null default 'new';
-- 5. copy values to the new column
update some_table set some_column = _some_column::text::some_enum_type;
-- 6. remove old column and type
alter table some_table drop column _some_column;
drop type _some_enum_type;

如果有多个列,则需重复步骤3-6。

0
0 Comments

PostgreSQL 9.1引入了改变枚举类型ALTER的能力:

ALTER TYPE enum_type ADD VALUE 'new_value'; -- appends to list
ALTER TYPE enum_type ADD VALUE 'new_value' BEFORE 'old_value';
ALTER TYPE enum_type ADD VALUE 'new_value' AFTER 'old_value';

0