語法結構
DECLARE
CURSOR cursor_name IS SELECT ...;
BEGIN
FOR record_var IN cursor_name LOOP
-- 處理 record_var.欄位
END LOOP;
END;
/
完整範例:列印所有員工姓名與薪資
DECLARE
CURSOR emp_cursor IS SELECT ename, sal FROM emp;
BEGIN
FOR emp_record IN emp_cursor LOOP
DBMS_OUTPUT.PUT_LINE('姓名: ' || emp_record.ename || ' , 薪資: ' || emp_record.sal);
END LOOP;
END;
/
執行結果
anonymous block completed
姓名: SMITH , 薪資: 880
姓名: ALLEN , 薪資: 1600
姓名: WARD , 薪資: 1250
姓名: JONES , 薪資: 3272.5
姓名: MARTIN , 薪資: 1250
姓名: BLAKE , 薪資: 2850
姓名: CLARK , 薪資: 2450
姓名: SCOTT , 薪資: 2000
姓名: KING , 薪資: 5000
姓名: TURNER , 薪資: 1500
姓名: ADAMS , 薪資: 1210
姓名: JAMES , 薪資: 950
姓名: FORD , 薪資: 3300
姓名: MILLER , 薪資: 2100
優缺點提醒
- 優點:隱性 OPEN/FETCH/CLOSE,程式碼簡潔
- 缺點:逐列處理(Row-by-row),大量資料效能差,應優先考慮集合操作(BULK COLLECT / FORALL)