Upgrading a varchar column to enum type in postgresql

旧城冷巷雨未停 提交于 2019-11-27 02:42:14

问题


We have a varchar column in a table, that we need to upgrade to enum type.

All the values in the varchar column are valid values in the enumeration. There is no null values in the varchar column.

ALTER TABLE tableName
   ALTER COLUMN varcharColumn TYPE enum_type

ERROR: column "varcharColumn" cannot be cast to type enum_type SQL state: 42804

The round about way is to

  1. Create another new column with enum type.
  2. Update the enum type column with the varchar column after typecasting.
  3. Drop the varchar column.
  4. Rename the enum type column name to the varchar column name.

Is there a better way to achieve this?

Thanks in advance.


回答1:


You need to define a cast to be used because there is no default cast available.

If all values in the varcharColumn comply with the enum definition, the following should work:

alter table foo 
  ALTER COLUMN varcharColumn TYPE enum_type using varcharColumn::enum_type;

I personally don't like enums because they are quite unflexible. I prefer a check constraint on a varchar column if I want to restrict the values in a column. Or - if the list of values changes often and is going to grow - a good old "lookup table" with a foreign key constraint.




回答2:


Got it.

ALTER TABLE tableName
   ALTER COLUMN varcharColumn TYPE enum_type
    USING varcharColumn::enum_type

will update it successfully.



来源:https://stackoverflow.com/questions/15655820/upgrading-a-varchar-column-to-enum-type-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!