title: Refactor a PL/pgSQL function to return the output of various SELECT queries
body: <p>I wrote a function that outputs a PostgreSQL <code>SELECT</code> query well formed in text form. Now I don't want to output a text anymore, but actually run the generated <code>SELECT</code> statement against the database and return the result - just like the query itself would.</p>
  <h3>What I have so far:</h3>
  <pre><code>CREATE OR REPLACE FUNCTION data_of(integer)
    RETURNS text AS
  $BODY$
  DECLARE
     sensors varchar(100);   -- holds list of column names
     type    varchar(100);   -- holds name of table
     result  text;           -- holds SQL query
         -- declare more variables
  
  BEGIN
        -- do some crazy stuff
  
        result := 'SELECT\r\nDatahora,' || sensors ||
        '\r\n\r\nFROM\r\n' || type ||
        '\r\n\r\nWHERE\r\id=' || $1 ||'\r\n\r\nORDER BY Datahora;';
  
        RETURN result;
  END;
  $BODY$
  LANGUAGE 'plpgsql' VOLATILE;
  ALTER FUNCTION data_of(integer) OWNER TO postgres;
  </code></pre>
  <p><code>sensors</code> holds the list of column names for the table <code>type</code>. Those are declared and filled in the course of the function. Eventually, they hold values like:</p>
  <ul>
  <li><p><code>sensors</code>: <code>'column1, column2, column3'</code><br />
  Except for <code>Datahora</code> (<code>timestamp</code>) all columns are of type <code>double precision</code>.</p>
  </li>
  <li><p><code>type</code> :<code>'myTable'</code><br />
  Can be the name of one of four tables. Each has different columns, except for the common column <code>Datahora</code>.</p>
  </li>
  </ul>
  <p><a href="http://pastebin.com/A2tZ9K3Q" rel="noreferrer"><strong>Definition of the underlying tables</strong>.</a></p>
  <p>The variable <code>sensors</code> will hold <em>all</em> columns displayed here for the corresponding table in <code>type</code>. For example: If <code>type</code> is <code>pcdmet</code> then <code>sensors</code> will be <code>'datahora,dirvento,precipitacao,pressaoatm,radsolacum,tempar,umidrel,velvento'</code></p>
  <p>The variables are used to build a <code>SELECT</code> statement that is stored in <code>result</code>. Like:</p>
  <pre><code>SELECT Datahora, column1, column2, column3
  FROM   myTable
  WHERE  id=20
  ORDER  BY Datahora;
  </code></pre>
  <p>Right now, my function returns this statement as <code>text</code>. I copy-paste and execute it in pgAdmin or via psql. I want to automate this, run the query automatically and return the result. How can I do that?</p>