2017-10-06 60 views
1

我是Oracle和數據庫的新手。新手到DB - Oracle

我想用遊標編寫存儲過程。我該如何在遊標循環中編寫select語句,以及如何循環從遊標循環中的select中得到的結果集?

例如:

Open Curs1; 
    Exit When Curs1%NotFound; 
    Loop 
     Select column1,column2 from table -- Returns multiple records. How to loop through this record set and perform CRUD operations. 
    End loop; 
    Close Curs1; 

回答

0

您需要在循環申報CURSORFETCH記錄。

DECLARE 
CURSOR curs1 
IS 
    SELECT column1, 
     column2 
    FROM yourtable; 

    v_column1 yourtable.column1%TYPE; 
    v_column2 yourtable.column2%TYPE; 
BEGIN 
OPEN curs1; 
    LOOP 

    FETCH curs1 
    INTO v_column1, 
      v_column2; 
    EXIT 
    WHEN curs1%NOTFOUND; 

    INSERT INTO yourtable2(col1)VALUES('000'||v_column1 ); 
    -- A sample DML operation. 

    --Do other operations on individual records here. 
    END LOOP; 
    CLOSE curs1; 
END; 
+0

您缺少'open curs1',應該先取,然後在未找到curs1%時使用exit。 –

+0

謝謝!這是編輯錯誤,未經測試... :) –

0

嘗試使用以下示例,在從光標可變emp_cv一個時間到用戶定義記錄EMP_REC提取行之一:

declare 
    TYPE YourType IS ref cursor return YourTable%rowtype; 
    tab_cv YourType; 
    tab_rec YourTable%rowtype; 
begin 
    loop 
     fetch tab_cv into emp_rec; 
     exit when tab_cv%notfound; 
     ... 
    end loop; 
end; 

散裝COLLECT子句允許您取結果集中的整個列或整個結果集。以下示例中,從一個遊標檢索列到收集:

declare 
    type NameList IS table of emp.ename%type; 
    names NameList; 
    cursor c1 is select ename from emp where job = 'CLERK'; 
begin 
    open c1; 
    fetch c1 bulk collect into names; 
    ... 
    close c1; 
end; 

以下示例使用LIMIT子句。對於循環的每次迭代,FETCH語句將100行(或更少)讀入索引表acct_ids。以前的值被覆蓋。

declare 
    type NumList is table of number index by binary_integer; 
    cursor c1 is select acct_id from accounts; 
    acct_ids NumList; 
    rows natural := 100; -- set limit 
begin 
    open c1; 
    loop 
     /* The following statement fetches 100 rows (or less). */ 
     fetch c1 bulk collect into acct_ids limit rows; 
     exit when c1%notfound; 
     ... 
    end loop; 
    close c1; 
end; 
2

使用for循環光標 - 它們比打開/讀取/關閉語法更快,更簡單。

begin 
    for results1 in 
    (
     select ... 
    ) loop 
     --Do something here 
     for results2 in 
     (
      select ... 
      where some_table.some_column = results1.some_column 
     ) loop 
      --Do something here 
     end loop; 
    end loop; 
end; 
/

雖然這個字面上回答了這個問題,但您通常不希望像這樣在循環內部存在循環。如果可能的話,最好將兩個SQL語句與一個連接組合起來,然後遍歷結果。