Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

sql - Upgrading a varchar column to enum type in postgresql

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...