是否可以在 psql 中过滤列名本身?我想在一个单独的模式(伪代码)中生成原始表的有限版本(具有数百列):
create table why.am_i_doing_this
select *
from original.table
where column_name_of_the_table not in ('column_1', 'column_2' );
动态构建 DDL 命令。您可以分两步完成:
-
构建语句:
SELECT 'CREATE TABLE why.am_i_doing_this AS SELECT '
|| string_agg(column_name, ', ' ORDER BY ordinal_position)
|| ' FROM original.table'
FROM information_schema.columns
WHERE table_schema = 'original'
AND table_name = 'table'
AND column_name NOT IN ('column_1', 'column_2');
(检查它是否正常!)然后在到服务器的第二次往返中执行生成的语句。
这是基于信息模式视图information_schema.columns。或者,您可以使用pg_catalog.pg_attribute。有关的:
但它也可以在到服务器的单次往返中完成:
With a DO
任何客户的声明
DO
只是一个简单的包装器,用于临时执行 PL/pgSQL 代码。您可以在函数或过程中执行相同的操作。
DO
$$
BEGIN
EXECUTE (
SELECT 'CREATE TABLE why.am_i_doing_this AS SELECT '
|| string_agg(column_name, ', ' ORDER BY ordinal_position)
|| ' FROM original.table'
FROM information_schema.columns
WHERE table_schema = 'original'
AND table_name = 'table'
AND column_name NOT IN ('column_1', 'column_2')
);
END
$$;
使用 psql 元命令更简单\gexec
既然你提到了默认交互终端psql。在那里你可以使用\gexec
. It ...
将当前查询缓冲区发送到服务器,然后将查询输出(如果有)的每行的每一列视为要执行的 SQL 语句。
So:
SELECT 'CREATE TABLE why.am_i_doing_this AS SELECT '
|| string_agg(column_name, ', ' ORDER BY ordinal_position)
|| ' FROM original.table'
FROM information_schema.columns
WHERE table_schema = 'original'
AND table_name = 'table'
AND column_name NOT IN ('column_1', 'column_2')\gexec
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)