title: PL/pgSQL: merge results from iterative function call in another function
body: <p>I have a function <code>func1(ID int)</code> that returns rows for a given ID.</p>
  
  <p>I have another function <code>func2(IDs int[])</code> that gets an array of IDs and uses a loop to call <code>func1</code> for each ID, finally it should combine all results and return it.</p>
  
  <p>Both functions return <code>SETOF y</code> so they are compatible in their schema of columns.</p>
  
  <p>What I want to do is inside the loop of <code>func2()</code> to merge the results. If it was in the same SQL query I would simply use <code>UNION</code> but the results are from a function. </p>
  
  <pre><code>CREATE OR REPLACE FUNCTION func2(IDs integer[]) RETURNS SETOF y AS
  $BODY$
  declare 
      a_id int;
      r y;
  begin
    FOREACH a_id IN ARRAY $1
    LOOP
      SELECT * into r FROM  func1(a_id) ; 
      //CODE TO ENTER FOR UNION EACH ITERATION WITH THE LAST ONE
    END LOOP;
  return;
  end;
  $BODY$ LANGUAGE plpgsql VOLATILE
  </code></pre>
  
  <p><code>r</code> should contain the result of a single call to <code>func1()</code>. How do I combine all <code>r</code> and return them?</p>
  
  <p>In simple words it should do: <code>func1(1st ID) UNION func1(2nd ID) UNION ... UNION func1(nth ID)</code> and return it to whom ever called <code>func2(IDs int[])</code>.</p>