PostgreSQL цикл FOR


In the process of writing a function for postgresql, a problem arose: it is necessary to form a SQL query, and subsequently "feed" it to the FOR loop. And since the request is generated dynamically (depending on the conditions), then I did not think of anything better than writing it into a variable of type text . The loop refuses to accept a string as a SQL query. Sample:

    table_string RECORD;
    query_string text := '';

query_string := 'SELECT * FROM tablename';

-- проблемный цикл
FOR table_string IN query_string
   -- какой-то код

The plpgsql function language.

pgAdmin III: "Syntax error (approximate position of" query_string ") LINE 10: FOR table_string IN query_string" (refers to table_string)

How to solve this problem? Thanks in advance!


This solution was suggested by the author of the question in his previous post.

The solution turned out to be much simpler:

FOR table_string IN EXECUTE query_string

It was enough to add EXECUTE before the variable containing the SQL query.

Scroll to Top