If there are no rows in result, empy table with key columns should returned intead of raising "upper bound of for loop" exception. Add those lines
execute ('create temp table ' || in_table || ' on commit drop as ' || in_query);
-- Start of added lines
GET DIAGNOSTICS Arv = ROW_COUNT;
if Arv = 0 then
Execute 'create temp table ' || quote_ident(out_table) || ' on commit drop as select * from '||in_table ;
return;
end if;
-- End of added lines
...
If there are no rows in result, empy table with key columns should returned intead of raising "upper bound of for loop" exception. Add those lines