You could open a cursor for the query without the rownum condition and fetch until you run out of data or hit an 11th row:
declare
l_query varchar2(4000) := '<your query without rownum condition>';
l_counter pls_integer := 0;
l_cursor sys_refcursor;
l_row gtt%rowtype;
begin
open l_cursor for l_query;
loop
fetch l_cursor into l_row;
exit when l_cursor%notfound;
l_counter := l_counter + 1;
if l_counter > 10 then
dbms_output.put_line('Query got more than 10 rows');
exit;
end if;
-- first 1-10 rows so insert
insert into gtt values l_row;
end loop;
end;
/
Or with a collection to make it slightly more efficient:
declare
l_query varchar2(4000) := '<your query without rownum condition>';
l_cursor sys_refcursor;
type t_tab is table of gtt%rowtype;
l_tab t_tab;
begin
open l_cursor for l_query;
-- fetch gets at most 10 rows
fetch l_cursor bulk collect into l_tab limit 10;
-- up to 10 rows found are inserted
forall i in 1..l_tab.count
insert into gtt values l_tab(i);
-- fetch again, if it finds anything then total row count > 10
fetch l_cursor bulk collect into l_tab limit 1;
if l_cursor%found then
dbms_output.put_line('Query got more than 10 rows');
end if;
close l_cursor;
end;
/
However, the optimiser can often use a rownum condition to reduce the work it has to do (via a stopkey which you can see in the execution plan). It might still be faster and more efficient to run the query twice, once with the 10-row limit for the insert, and again with an 11-row limit to just get the count, and see if that is 11 or not. You should test both approaches to see which is actually better for you data. (And any others that are suggested, of course!)
where rownum = 10will not return any rows because of howrownumworks. Andwhere rownum<=10won't insert more than 10 rows. An MCVE would help us understand what you are actually doing and the issue you have. Are you trying to see how many rows the query would find without that condition, but still only insert the first 10 rows into the GTT?execute immediate insert into gtt select *from query were rownum<=10