postgresql - 使用存储的名称创建多个模式
问题描述
我正在尝试在我的 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
$$;
解决方案
您的代码有两个问题:首先,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
$$;
推荐阅读
- c - 如何修复由-Wconversion引起的错误?
- html - 如何修改我的 css 或 cshtml 以获得类似于 w3school 上的下拉导航栏?
- python - Python代码在程序/代码的开头跳回?
- firebase - 我将如何每周运行一次 javascript 代码?
- gtfs - 什么信息来源是交通 Web 应用程序的行业标准 - GTFS 与 Trapeze 数据文件
- python-3.x - 无法为 python 3 安装 openssl
- node.js - 如何将字符串添加到“错误数组”?
- blazor - 是否可以在 Blazor 中混合使用客户端和服务器端方法?
- asp.net - 为什么 TransactionScope 不为我的以下 SQL 命令启动事务
- c - 无法启动递归互斥锁