如何在一次操作中更改多个 PostgreSQL 表的架构?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10218768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-20 23:50:00  来源:igfitidea点击:

How to change schema of multiple PostgreSQL tables in one operation?

postgresqlschemamigratepostgresql-9.1

提问by RyanKDalton

I have a PostgreSQL 9.1 database with 100 or so tables that were loaded into the 'public' schema. I would like to move those tables (but not all of the functions in 'public') to a 'data' schema.

我有一个 PostgreSQL 9.1 数据库,其中包含 100 个左右的表,这些表已加载到“公共”模式中。我想将这些表(但不是“公共”中的所有功能)移动到“数据”模式。

I know that I can use the following to move 1 table at a time.

我知道我可以使用以下方法一次移动 1 个表。

ALTER TABLE [tablename] SET SCHEMA [new_schema]

Is it possible to move all of the tables to the new schema in one operation? If so, what would be the most efficient way to accomplish this task?

是否可以在一次操作中将所有表移动到新模式?如果是这样,完成这项任务的最有效方法是什么?

回答by Frank Heikens

DOwill do the trick:

DO将这样的伎俩:

DO
$$
DECLARE
    row record;
BEGIN
    FOR row IN SELECT tablename FROM pg_tables WHERE schemaname = 'public' -- and other conditions, if needed
    LOOP
        EXECUTE 'ALTER TABLE public.' || quote_ident(row.tablename) || ' SET SCHEMA [new_schema];';
    END LOOP;
END;
$$;