postgresql - Concatenate result of a SELECT into an EXECUTE
问题描述
I am trying to recreate a view from a backup of the definition using EXECUTE in an anonymous code block (DO $$ ... BEGIN... END$$
), but I cannot get it to work. This is approximately what I have so far:
EXECUTE 'CREATE VIEW image AS (' || (SELECT definition FROM tmp_view_backup WHERE viewname = 'image') || ')';
The table with the backup of the view definitions was made like this
CREATE TABLE tmp_view_backup
AS
(select viewname,definition from pg_views
WHERE schemaname = 'public'
);
It seems like it is the select that causes me some problems in creating the string, as the result is not at all what I anticipated:
postgres=# select char_length('CREATE VIEW image AS (' || (SELECT definition FROM tmp_view_backup WHERE viewname = 'image') || ')') as f ;
f
---
(1 row)
What is this? An empty row? If I drop the select I get a normal answer (like the string length being 23
).
解决方案
You can make use of PSQL \gexec
parameter.
SELECT format('CREATE VIEW image AS %s ', definition)
FROM tmp_view_backup
WHERE viewname = 'image';\gexec
Or in a DO block
DO $$
BEGIN
EXECUTE format('CREATE VIEW image AS %s ', definition)
FROM tmp_view_backup
WHERE viewname = 'image';
END $$;
推荐阅读
- node.js - 在nodejs中使用argparse在cmd中传递对象
- c# - 无法解析范围服务 DbContextOptions
- php - 我的 Laravel 应用程序在 Google Cloud 上出现问题。无法打开流或文件“/srv/storage/logs/laravel.log”
- sql - 在第二个分号之后和第一个连字符之前解析字符串的正则表达式
- java - 从 Java 运行带有参数的 python 脚本,作为 exe
- excel - 我的宏使文件变大,尽管它删除了信息
- mysql - MYSQL BETWEEN 运算符
- html - 如何在不滚动页面的情况下加载图像?
- javascript - React Native - CheckBox 无法取消选中“已选中”框
- three.js - 如何统一(相同大小的复选框)自定义方格纹理图像,应用于三个 Js 中加载的模型的所有对象?