如何通过sql将枚举转换成字符串值(甲骨文)

qmb5sa22  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(669)

我有一个oracledb表,其中枚举保存为整数,但我想更新该表,将所有枚举保存为字符串值。我想使用现有的整数枚举列作为新的字符串值。
注意:我使用的是hibernate。我在补充 @Enumerated(EnumType.STRING) 添加到实体类中的枚举,以便将来将它们保存为字符串。但我想更新现有的表,而不是删除并重新创建它们。

初始表

id=1,name='lucky',species=3
id=2,name='spot',species=1

期望的表

id=1,name='lucky',species='lizard'
id=2,name='spot',species='dog'
其中species是一个类似enum的物种(“狗”、“猫”、“蜥蜴”)

63lcw9qa

63lcw9qa1#

基本上,您需要做4件事:添加列、填充列、删除旧列,然后将新列重命名为旧列。它看起来像:

alter table mytable add (species_1 varchar2(30 char));

update mytable set species_1 = ( [select the species name based on the integer value somehow]);

alter table mytable drop column species;

alter table mytable rename species_1 to species;

alter table mytable modify ( species_1 varchar2(30 char) not null);

alter table mytable add ( constraint species_ck check species in ('DOG', 'CAT', 'LIZARD' );

但在我看来,这是糟糕的数据库设计。您应该拥有的是作为整数的枚举和一个小维度表,其中列出了所有可能的值,以及事实表上的外键约束。如果需要物种的名称,请创建一个视图。

相关问题