不,您不能使用for
循環瀏覽動態構建的查詢返回的結果集。但是,你不能做的是爲該動態構建的查詢打開一個refcursor
,並使用LOOP
或WHILE
循環結構遍歷結果集。舉個簡單的例子,但在你的情況,沒有必要使用動態SQL可言:
set serveroutput on;
clear screen;
declare
l_sql_statement varchar2(4000); -- going to contain dynamically built statement
l_rcursor sys_refcursor; -- ref cursor
l_owner varchar2(100); -- variable that will contain owner's name
l_res_tab_name varchar2(100); -- variable we will fetch table name into
begin
l_owner := 'NK';
l_sql_statement := 'select table_name
from all_tables
where owner = :1'; -- bind variable
open l_rcursor for l_sql_statement
using dbms_assert.simple_sql_name(l_owner); -- slight protection from
-- SQL injection
loop
fetch l_rcursor into l_res_tab_name; -- fetch table name from the resultset
exit when l_rcursor%notfound; -- exit, when there is nothing to fetch
dbms_output.put_line(l_res_tab_name); -- print table name
end loop;
end;
結果:
anonymous block completed
TEST1
TEST2
TMP_TEST
ERR$_T1
注:考慮,在這種情況下,根本不使用動態SQL,實際上不需要它。表名和列名在編譯時是已知的,只有謂詞的右側發生了變化。
+1 **注**。 [帶參數的光標](http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/explicit_cursor.htm#LNPLS01313)就足夠了。 –