PostgreSQL:将列名放入数组 PL/pgSQL
PostgreSQL: column names into array PL/pgSQL
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');
提供一个 table 名称并希望将其列名作为数组返回。上面的代码给出了'syntax error at or near "array"'。如何解决这个问题?
查询应以 select
开头,而不是 array
并且不必是动态的 SQL。
试试这个修改后的版本:
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';
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');
提供一个 table 名称并希望将其列名作为数组返回。上面的代码给出了'syntax error at or near "array"'。如何解决这个问题?
查询应以 select
开头,而不是 array
并且不必是动态的 SQL。
试试这个修改后的版本:
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';