【问题标题】:CREATE MULTIPLE SCHEMA using a name stored使用存储的名称创建多个模式
【发布时间】:2021-03-09 17:47:28
【问题描述】:

我正在尝试在我的 postgres 数据库上创建新模式,其名称存储在现有表中, 我的查询如下所示:

DO $$
    declare s_name text;
BEGIN

    IF NOT EXISTS(
        SELECT schema_name
          FROM information_schema.schemata
          
    THEN
        SELECT name INTO s_name FROM table_name;
        execute 'create schema '|| quote_ident(s_name);
    Raise notice 'status:%', schema created successfully;
    END IF;

END
$$;

【问题讨论】:

  • 你的问题到底是什么?
  • 现有表中存储了多个值,因此需要动态创建多个模式并且不应该存在,尝试循环它但卡在中间

标签: postgresql


【解决方案1】:

您的代码有两个问题:首先,if not exists 永远不会为真,因为 select 将始终返回至少一行,因为每个 Postgres 数据库中至少有三个模式。您实际上并不需要该检查,因为您可以使用 create schema if not exists

第二个问题是,您没有循环遍历结果,您只是选择了该表的一行。

DO $$
declare 
  l_rec record;
BEGIN
    FOR l_rec IN select name from table_name
    LOOP 
      execute format('create schema if not exists %I', l_rec.name);
    END loop;
END
$$;

【讨论】:

  • 感谢您的快速回复,是的,它正在工作。在这里我有一个疑问。是否可以在创建时连接字符串和模式名称。 EX:名称是-“Test”,我想创建像“Test_First”这样的模式(执行格式('如果不存在则创建模式%I',l_rec.name'||'_first);)。
猜你喜欢
  • 2023-03-21
  • 2017-09-24
  • 2020-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多