What is wrong in my dynamic query postgres statements inside function?
<p>I have a PL/pgSQL function that takes table name as dynamic parameter. As I am updating an existing query to take table name as dynamic parameter, this is what I have as my function: </p>

<pre><code>DECLARE rec RECORD; 
BEGIN 
  EXECUTE 'insert into stat_300_8_0(ts, target, data)
               select distinct timestamp-(timestamp%3600) as wide_row_ts,
                      target, array[]::real[] as data
               from ' || temp_table_name || ' as temp 
               where class_id=8
                 and subclass_id=0 
                 and not exists (select ts from stat_300_8_0 
                                 where ts=temp.timestamp-(temp.timestamp%3600)
                                 and target=temp.target)'; 

  FOR rec IN EXECUTE 'SELECT DISTINCT timestamp AS ts 
                      FROM ' || temp_table_name ||
                    ' WHERE class_id=8' 
  LOOP 
      EXECUTE 'update stat_300_8_0 as disk_table
               set data[new_data.start_idx:new_data.end_idx] = array[data_0,data_1]
               from (select timestamp-(timestamp%3600) as wide_row_ts,
                            (timestamp%3600)/300 * 2 + 1 as start_idx,
                            ((timestamp%3600 / 300) + 1) * 2 as end_idx,
                            target, data_0, data_1
                     from ' || temp_table_name ||
                   ' where class_id=8 and subclass_id=0
                       and timestamp=rec.ts) as new_data
               where disk_table.ts=new_data.wide_row_ts
                 and disk_table.target=new_data.target';
  END LOOP; 
END;
</code></pre>

<p>However, when this function is executed I get an error saying </p>

<pre><code>ERROR:  missing FROM-clause entry for table "rec"
</code></pre>

<p>However, <code>rec</code> is declared in the first line of the above code. I am not able to figure what is wrong with my queries. Any help is appreciated.</p>