2014-02-26 92 views
0

下面的代碼是不言自明的。我們可以在PL/SQL的FOR-IN循環中使用變量嗎? 這是要求,因爲FOR-IN內部的查詢需要具有動態性質。我們可以在FOR-IN循環中使用變量嗎

SET SERVEROUT ON; 

DECLARE 
    STMNT  varchar2(4000); 
    SELECT_SQL varchar2(4000); 
BEGIN 
    SELECT_SQL := q'[select table_name from all_tables where owner='EMP' and table_name like 'TEMP_%']'; 
    FOR REC IN (SELECT_SQL) LOOP 
     dbms_output.put_line (REC.table_name); 
    END LOOP; 
END; 

回答

3

不,您不能使用for循環瀏覽動態構建的查詢返回的結果集。但是,你不能做的是爲該動態構建的查詢打開一個refcursor,並使用LOOPWHILE循環結構遍歷結果集。舉個簡單的例子,但在你的情況,沒有必要使用動態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,實際上不需要它。表名和列名在編譯時是已知的,只有謂詞的右側發生了變化。

+2

+1 **注**。 [帶參數的光標](http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/explicit_cursor.htm#LNPLS01313)就足夠了。 –

相關問題