2013-08-16 3 views
7

오라클의 커서 for 루프를 사용하는 방법을 알려주십시오.오라클의 커서 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; 

다음 필요가 없습니다 open, fetch 또는 close 커서를 .

+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