在PostgreSQL中执行SQL作为选择查询结果字符串。

huangapple go评论49阅读模式
英文:

Execute SQL returned as a select query result string in PostgreSQL

问题

我有一个使用 SELECT functionName 运行的函数。它会返回一个包含另一个我想立即执行的SQL查询的单行,其中包含一个文本单元。在PostgreSQL中是否有执行这个操作的方法?

英文:

I've got a function that I run using SELECT functionName. It returns me a single row with a single text cell containing another SQL query that I'd like to execute right away. Is there any way to do this in PostgreSQL?

答案1

得分: 1

You'll have to use PL/pgSQL to execute dynamic SQL

In case that the returned cursor of the queries has a fixed structure (i.e. same column names and data types) you may define a function returning a TABLE

CREATE OR REPLACE FUNCTION exec_query(text)
RETURNS table (id int)
LANGUAGE 'plpgsql'
AS $$
BEGIN 
    RETURN QUERY  EXECUTE $1 ; 
END 
$$;

The usage is as follows

select * from exec_query('select id from generate_series(1,3) t(id)')
    
id|
--+|
 1|
 2|
 3|

In case the dynamic queries vary in the returned structure, define a function returning SETOF RECORD

CREATE OR REPLACE FUNCTION exec_query(text)
RETURNS SETOF RECORD
LANGUAGE 'plpgsql'
AS $$
BEGIN 
    RETURN QUERY  EXECUTE $1 ; 
END 
$$;

But you will have to add the column definition list to the call

select * from exec_query('select id from generate_series(1,3) t(id)') as t(id int);

Otherwise an error is raised ERROR: a column definition list is required for functions returning "record"

Similar question

英文:

You'll have to use PL/pgSQL to execute dynamic SQL

In case that the returned cursor of the queries has a fixed structure (i.e. same column names and data types) you may define a function retruning a TABLE

CREATE OR REPLACE FUNCTION exec_query(text)
RETURNS table ( id int)
LANGUAGE 'plpgsql'
AS $$
BEGIN 
    RETURN QUERY  EXECUTE $1 ; 
END 
$$;

The usage is as follows

select * from exec_query('select id from generate_series(1,3) t(id)')

id|
--+
 1|
 2|
 3|

In case the dynamic queries vary in the returned structure, define a function returning SETOF RECORD

CREATE OR REPLACE FUNCTION exec_query(text)
RETURNS SETOF RECORD
LANGUAGE 'plpgsql'
AS $$
BEGIN 
    RETURN QUERY  EXECUTE $1 ; 
END 
$$;

But you will have to add the column definition list to the call

select * from exec_query('select id from generate_series(1,3) t(id)') as t(id int);

Otherwise a error is raised ERROR: a column definition list is required for functions returning "record"

Similar question

huangapple
  • 本文由 发表于 2023年3月9日 21:28:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75685261.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定