是否可以将 EXECUTE 语句嵌套为 PostgreSQL 中的源记录集?

Is it possible to nest an EXECUTE statement as a source recordset in PostgreSQL?

这是动态 _sql select 传递给尝试执行查询的函数和 return 包含结果的 JSON 数组的情况。

create or replace function jlist_objects_bysql (
  _sql  varchar
)
returns json
as $$
  select
    json_agg (t)
  from (
    execute _sql
  ) as t;
$$ language sql;

PostgreSQL 12 中的验证错误是

psql:objects_procedures.sql:874: ERROR:  syntax error at or near "t"
LINE 8:   from execute _sql t;

动态 SQL 不适用于 language sql,但适用于 language plpgsql

然后,你可以放大动态查询

create or replace function jlist_objects_bysql (
  _sql  varchar
)
returns json
as $$
declare
    output json;
BEGIN
 execute 'select json_agg (t) from (   ' || _sql || '
  ) as t;'
  INTO output;
  
  return output;
END
$$ language plpgsql;


select jlist_objects_bysql('select * from test');