title: Passing table name to a function and returning a table
body: <p>I need to run the same query on many tables of a DB (PostgreSQL 9.3.5) and passing the table name as an argument to a function seems a logic thing to do. Reading at examples in the docs and numerous S.O. postings, I still cannot nail it down.</p>
  
  <p>Using this minimal example:</p>
  
  <pre><code>CREATE TABLE films (
  code        char(5),
  kind        varchar(10)
  );
  INSERT INTO films VALUES
  ('UA502', 'Comedy');
  </code></pre>
  
  <p>And this function:</p>
  
  <pre><code>CREATE OR REPLACE FUNCTION foo(_t text)
  RETURNS void AS  -- I know, void is not what I am after
  $func$
  BEGIN
     EXECUTE format('SELECT count(*) FROM %I', _t);
  END
  $func$  LANGUAGE plpgsql;
  </code></pre>
  
  <p>The following query catches something:</p>
  
  <pre><code>mydb=&gt; SELECT foo('films');
   foo
  -----
  (1 row)
  </code></pre>
  
  <p>However because I want to retrieve a table I edit the second line and re-create the function like so:</p>
  
  <pre><code>CREATE OR REPLACE FUNCTION foo(_t text)
  RETURNS TABLE(count integer) AS
  $func$
  BEGIN
     EXECUTE format('SELECT count(*) FROM %I', _t);
  END
  $func$  LANGUAGE plpgsql;
  </code></pre>
  
  <p>However the same query does not catch anything: </p>
  
  <pre><code>mydb=&gt; SELECT foo('films');
  foo
  -----
  (0 rows) 
  </code></pre>
  
  <p>Could someone let me know what I am missing here and how to proceed? Any hints greatly appreciated!</p>