1

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
  • Why does the function return SQL code as text in the first place? Commented Mar 9, 2023 at 13:47

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.