PostgreSQL动态列选择



我在一些动态postgresql上有点挣扎:我有一个名为list_columns的表;包含列名称列表的"column_name"作为变量名;这些列名来自一个名为"input_table"的输入表。

[list_columns]

tbody> <<tr>
column_name
col_name_a
col_name_b
col_name_c…

为此需要动态SQL,而为此需要PL/pgSQL。

您需要根据input_table组装CREATE TABLE语句,然后运行生成的SQL。

do
$$
declare
l_columns text;
l_sql text;
begin
-- this generates the list of columns
select string_agg(distinct column_name, ',')
into l_columns
from list_table;
-- this generates the actual CREATE TABLE statement using the columns
-- from the previous step
l_sql := 'create table output_table as select '||l_columns||' from input_table';
-- this runs the generated SQL, thus creating the output table.
execute l_sql;
end;
$$;

如果你非常需要它,你可以把它放在一个存储函数中(你不支持的Postgres版本不支持真正的过程)。

最新更新