我正在尝试在我的 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
$$;
答案 0 :(得分:0)
您的代码有两个问题:首先,if not exists
永远不会为真,因为选择将始终返回至少一行,因为每个 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
$$;