I need to return a resultset from function and work with this resultset just like with an ordinary table.
So I need something like following:
select
If I understand you correctly, you want to do this:
select * from (select * from dual)
...with the caveat that the subquery is in some way dynamic? You can do this using a PL/SQL block, using a reference cursor:
declare
subQuery varchar2(1000);
mainQuery varchar2(1000) := 'select * from (';
type myRefCursor is ref cursor;
myResultset myRefCursor;
myField1 FIELDTYPE;
...
myFieldN FIELDTYPE;
begin
-- Generate this dynamically
subQuery := 'select * from dual';
-- Create main query and open cursor
mainQuery := mainQuery || subQuery || ')';
open myResultset for mainQuery;
-- Loop through records
loop
fetch myResultset into myField1, ..., myFieldN;
exit when myResultset%NOTFOUND;
-- Do something with the record data
dbms_output.put_line(myField1 || ' ... ' || myFieldN);
end loop;
close myResultset;
end;
/
Note that rather than using fetch into
with individual variables, you can populate an entire record at once, provided you can define the record's field types. That is, if you have created a custom type or your record's type matches a table you already have in your schema. For the latter, you can use:
myRecord someTable%ROWTYPE;
...in the declaration block, then change the fetch into
statement to:
fetch myResultset into myRecord;
...and access record fields using dot notation (e.g., myRecord.some_field_name
).
You say in your comments that the dynamic SQL bit is from the results of some other query. Therefore, in my example code, you could use a regular cursor to loop over these data to create the subQuery
variable in each instance... Although, incidentally, is there any reason why what you're trying to achieve can't be done with a simple join
?