Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to execute a piece of code for each element of the result of a dynamic query in PostgreSQL?

I have a dynamic query in my PostgreSQL function:

execute format('select something from %', table_name)

I want to run some code for every record returned by the above statement.

How can I do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My first idea is as follows.

I need to do something like this:

execute format('select something from %', table_name)
into my_data;

for my_record in my_data
loop

-- Do something with my_record

end loop;

In order to use the above code in a function or procedure, I need to declare the variables my_data and my_record.

my_record has the data type record. What could the data type of my_data be?

>Solution :

You can use a dynamic statement in a FOR loop:

DECLARE
   r record;
BEGIN
   FOR r IN
      EXECUTE format('select something from %I', table_name)
   LOOP
      /* "r" now contains a table row */
   END LOOP;
END;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading