当文本值不匹配时,Postgres将文本转换为枚举

发布于 2025-02-04 08:33:56 字数 793 浏览 1 评论 0原文

我正在尝试将文本值转换为文本值不匹配新枚举的枚举值。 Postgres是否可以不必先删除列或在之前写一堆更新脚本?

CREATE TABLE "test_table" (
    "id" uuid NOT NULL DEFAULT uuid_generate_v4(),
    "shape" text
);

insert into test_table(shape) values ('Round');
insert into test_table(shape) values ('Square');

CREATE TYPE "public"."test_table_shape_enum" AS ENUM(
    'round',
    'square'
    );

ALTER TABLE test_table
    ALTER shape TYPE test_table_shape_enum USING shape::test_table_shape_enum;

[22P02] ERROR: invalid input value for enum test_table_shape_enum: "Round"

我看到这样做的几种方法是在进行Alter之前对所有行进行更新。

update test_table set shape='round' where shape='Round';
update test_table set shape='square' where shape='Square';

但是,如果我能做到这一点,那会很好。是否有更好的方法可以在运行Alter命令之前不必编写一堆更新脚本?

I'm trying to convert a column from text to enum value where the text values don't match the new enums. Is this possible with Postgres without having to drop the column first or write a bunch of update scripts prior?

CREATE TABLE "test_table" (
    "id" uuid NOT NULL DEFAULT uuid_generate_v4(),
    "shape" text
);

insert into test_table(shape) values ('Round');
insert into test_table(shape) values ('Square');

CREATE TYPE "public"."test_table_shape_enum" AS ENUM(
    'round',
    'square'
    );

ALTER TABLE test_table
    ALTER shape TYPE test_table_shape_enum USING shape::test_table_shape_enum;

[22P02] ERROR: invalid input value for enum test_table_shape_enum: "Round"

A few ways I see doing this is either do an update to all rows prior to doing the alter.

update test_table set shape='round' where shape='Round';
update test_table set shape='square' where shape='Square';

But it would be nice if I can do it with all one go; is there a better way of doing this without having to write a bunch of update scripts prior to running the alter command?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

与他有关 2025-02-11 08:33:56

如果唯一的问题是字母案例,请使用lower()

ALTER TABLE test_table
    ALTER shape TYPE test_table_shape_enum 
    USING lower(shape)::test_table_shape_enum;

db<> fiddle。

If the only problem is the letter case, use lower():

ALTER TABLE test_table
    ALTER shape TYPE test_table_shape_enum 
    USING lower(shape)::test_table_shape_enum;

Test it in Db<>Fiddle.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文