2013-08-16 57 views
7

請解釋一下如何在oracle中使用遊標循環。Oracle中的遊標for循環

如果我使用下一個代碼,一切都很好。

for rec in (select id, name from students) loop 
    -- do anything 
end loop; 

但是,如果我爲這個sql語句定義變量,它不起作用。

v_sql := 'select id, name from students'; 

for rec in v_sql loop 
    -- do anything 
end loop; 

錯誤:PLS-00103

回答

10

爲了解決與你的問題,你需要使用

遊標變量並打開遊標並獲取數據的方式明確的第二種方法相關的問題。這不是

允許使用遊標變量在FOR循環:

declare 
    l_sql varchar2(123);  -- variable that contains a query 
    l_c sys_refcursor;  -- cursor variable(weak cursor). 
    l_res your_table%rowtype; -- variable containing fetching data 
begin 
    l_sql := 'select * from your_table'; 

    -- Open the cursor and fetching data explicitly 
    -- in the LOOP. 

    open l_c for l_sql; 

    loop 
    fetch l_c into l_res; 
    exit when l_c%notfound; -- Exit the loop if there is nothing to fetch. 

    -- process fetched data 
    end loop; 

    close l_c; -- close the cursor 
end; 

Find out more

+1

最合適的答案。我想,這一切都會更容易。感謝您的決定。 –

5

試試這個:

cursor v_sql is 
select id, name from students; 

for rec in v_sql 
loop 
    -- do anything 
end loop; 

則無需openfetchclose光標。

+0

我認爲,如果我能在定義階段知道sql代碼,那麼這段代碼就可以工作,但它會在執行階段生成。 –

+0

您可以在遊標定義中定義參數,但僅限於where子句。如果你需要動態地設置表,那麼'OPEN c FOR string'可能就是要走的路。 –

0

如果您在運行時進行查詢,則必須使用Refcursor。實際上,refcursors是指向查詢的指針,它們不會爲獲取的行佔用任何空間。 正常遊標不適用於它。

declare 
v_sql varchar2(200); 
rec sys_refcursor; 
BEGIN 
v_sql := 'select id, name from students'; 

open rec for v_sql 
loop 
fetch 
exit when.... 
-- do anything 
end loop; 
2

您不在任何地方執行該sql字符串。只要做到這一點

v_sql := 'select id, name from students'; 
open cur for v_sql; 
for rec in cur loop 
    -- do anything 
end loop; 

或者你也可以做到這一點

cursor cur is select id, name from students; 
open cur; 
for rec in cur loop 
     -- do anything 
end loop; 

或者你可以現在做這個

for rec in (select id, name from students) loop 
    -- do anything 
end loop