在postgresql中将varchar列升级为枚举类型 [英] Upgrading a varchar column to enum type in postgresql

查看:539
本文介绍了在postgresql中将varchar列升级为枚举类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在表中有一个varchar列,我们需要升级到枚举类型。

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

varchar列中的所有值都是枚举中的有效值。在varchar列中没有空值。

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

错误:列varcharColumn不能转换为类型enum_type
SQL状态:42804

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

这种方式是


  1. 枚举类型。

  2. 在类型转换后,使用varchar列更新枚举类型列。

  3. 删除varchar列。

  4. 将枚举类型列名重命名为varchar列名称。

  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.

有更好的方法吗?

提前感谢。

推荐答案

您需要定义要使用的转换,因为没有可用的默认投射。

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

如果 varcharColumn 中的所有值都符合枚举定义,则以下内容应该适用:

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;

我个人不喜欢枚举,因为它们相当不灵活。如果我想限制列中的值,我更喜欢varchar列上的检查约束。或者 - 如果值列表经常变化并且会增长 - 一个旧的查找表,带有外键约束。

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.

这篇关于在postgresql中将varchar列升级为枚举类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆