[英]Filter column names from existing table for SQL DDL statement
Is it possible to filter on column names themselves in psql?是否可以在 psql 中过滤列名本身? I want to generate a limited version of the original table (with several hundred columns) in a separate schema a la (pseudocode):我想在单独的模式 a la(伪代码)中生成原始表的有限版本(有几百列):
create table why.am_i_doing_this
select *
from original.table
where column_name_of_the_table not in ('column_1', 'column_2' );
Build the DDL command dynamically.动态构建 DDL 命令。 You can do it in two steps:您可以分两步完成:
Build statement:构建声明:
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');
(Check it's good.) Then execute the generated statement in a second round trip to the server. (检查它是否良好。)然后在服务器的第二次往返中执行生成的语句。
This is based on the information schema viewinformation_schema.columns
.这基于信息模式视图information_schema.columns
。 Alternatively, you could use pg_catalog.pg_attribute
.或者,您可以使用pg_catalog.pg_attribute
。 Related:有关的:
But it can be done in a single round trip to the server, too:但它也可以在与服务器的单次往返中完成:
DO
statement from any client来自任何客户的DO
声明DO
is just a simple wrapper for ad-hoc execution of PL/pgSQL code. DO
只是用于临时执行 PL/pgSQL 代码的简单包装器。 You might do the same in a function or procedure.您可以在 function 或过程中执行相同的操作。
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
$$;
\gexec
使用 psql 元命令\gexec
更简单Since you mentioned the default interactive terminal psql
.既然您提到了默认的交互式终端psql
。 There you can use \gexec
.在那里你可以使用\gexec
。 It...它...
Sends the current query buffer to the server, then treats each column of each row of the query's output (if any) as a SQL statement to be executed.将当前查询缓冲区发送到服务器,然后将查询的 output(如果有)的每一行的每一列视为要执行的 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.