You can't reference the cursor_loop
directly in your dynamic SQL because of the scope, as other have already said. If you are stuck with this pattern then you could use a bind variable flag to pass state information from the dynamic code back to the static code; something like:
DECLARE
break_loop pls_integer;
...
break_loop := 0;
<<cursor_loop>>
LOOP
fetch c1 into somerecord;
EXECUTE IMMEDIATE 'begin if 1 = 1 then :break_loop := 1; end if; end;'
USING OUT break_loop;
EXIT cursor_loop WHEN break_loop = 1;
END LOOP cursor_loop;
...
Slightly more complete, though obviously still horribly contrived, example:
DECLARE
break_loop pls_integer;
somevar number;
c1 sys_refcursor;
BEGIN
OPEN c1 FOR
select 1 from dual
union all select 2 from dual
union all select 3 from dual;
break_loop := 0;
dbms_output.put_line('before loop, break_loop is ' || break_loop);
<<cursor_loop>>
LOOP
fetch c1 into somevar;
exit when c1%notfound;
dbms_output.put_line('got ' || somevar);
EXECUTE IMMEDIATE 'begin if :somevar = 2 then :break_loop := 1; end if; end;'
USING somevar, OUT break_loop;
EXIT cursor_loop WHEN break_loop = 1;
END LOOP cursor_loop;
dbms_output.put_line('after loop, break_loop is ' || break_loop);
END;
/
PL/SQL procedure successfully completed.
before loop, break_loop is 0
got 1
got 2
after loop, break_loop is 1
The loop is exited because of the dynamic check, before the value '3' is fetched.