PostgreSQL: column names into array PL/pgSQL

眉间皱痕 提交于 2019-12-24 22:03:32

问题


create or replace function extr( tabname text ) returns text[] as
$$
declare cols text[];
begin
    execute 'array(select column_name::text from information_schema.columns where table_name = '||quote_literal(tabname)||');' into cols;
    return cols;
end;
$$
language 'plpgsql';

select extr('test');

One supplies a table name and wants back its column-names as an array. The above code gives 'syntax error at or near "array"'. How to fix this?


回答1:


The query should start with select, not array and it doesn't have to be dynamic SQL.

Try this modified version:

create or replace function extr( tabname text ) returns text[] as
$$
declare cols text[];
begin
    select array(select column_name::text from information_schema.columns
      where table_name = tabname) into cols;
    return cols;
end;
$$
language 'plpgsql';


来源:https://stackoverflow.com/questions/32541292/postgresql-column-names-into-array-pl-pgsql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!