CREATE OR REPLACE FUNCTION process_performance_data_proc()
 RETURNS VOID
 LANGUAGE plpgsql
 VOLATILE
 AS
 $$
 DECLARE
   l_counter_value       vpx_dbm_counter_value.counter_value%TYPE;
   l_last_sample_time    vpx_dbm_counter_value.sample_time%TYPE;
   l_rec_metadata        record;
 BEGIN
   
   FOR l_rec_metadata IN ( SELECT counter_id,
                                sql_statement,
                                keep_days
                           FROM vpx_dbm_counter_metadata )
   LOOP
     BEGIN
       EXECUTE l_rec_metadata.sql_statement INTO l_counter_value;
 
       INSERT INTO vpx_dbm_counter_value (counter_id, counter_value)
       VALUES (l_rec_metadata.counter_id, ROUND(l_counter_value));
 
       EXCEPTION WHEN OTHERS
         THEN NULL;
     END;
 
   
   SELECT MAX(sample_time)
     INTO l_last_sample_time
     FROM vpx_dbm_counter_value
    WHERE counter_id = l_rec_metadata.counter_id;
 
   
   DELETE FROM vpx_dbm_counter_value
    WHERE counter_id = l_rec_metadata.counter_id
      AND sample_time <= l_last_sample_time - (l_rec_metadata.keep_days || ' days')::interval;
   END LOOP;
 
 END
 $$