記錄變量
定義一個記錄變量使用TYPE命令和%ROWTYPE
例:
SET SERVERIUTPUT ON
DECLARE
R_emp EMP%ROWTYPE;
CURSOR c_emp IS SELECT * FROM emp;
BEGIN
OPEN c_emp;
LOOP
FETCH c_emp INTO r_emp;
EXIT WHEN c_emp%NOTFOUND;
DBMS_OUT
END LOOP;
CLOSE c_emp;
END;
%ROWTYPE也可以用游標名來定義
SET SERVERIUTPUT ON
DECLARE
CURSOR c_emp IS SELECT ename
R_emp c_emp%ROWTYPE;
BEGIN
OPEN c_emp;
LOOP
FETCH c_emp INTO r_emp;
EXIT WHEN c_emp%NOTFOUND;
DBMS_OUT
END LOOP;
CLOSE c_emp;
END;
帶參數的游標
與存儲過程和函數相似
CURSOR cursor_name[(parameter[
定義參數的語法如下:
Parameter_name [IN] data_type[{:=|DEFAULT} value]
與存儲過程不同的是
另外可以給參數設定一個缺省值
在打開游標時給參數賦值
OPEN cursor_name[value[
參數值可以是文字或變量
例:
DECALRE
CURSOR c_dept IS SELECT * FROM dept ORDER BY deptno;
CURSOR c_emp (p_dept VARACHAR
SELECT ename
FROM emp
WHERE deptno=p_dept
ORDER BY ename
r_dept DEPT%ROWTYPE;
v_ename EMP
v_salary EMP
v_tot_salary EMP
BEGIN
OPEN c_dept;
LOOP
FETCH c_dept INTO r_dept;
EXIT WHEN c_dept%NOTFOUND;
DBMS_OUTPUT
v_tot_salary:=
OPEN c_emp(r_dept
LOOP
FETCH c_emp INTO v_ename
EXIT WHEN c_emp%NOTFOUND;
DBMS_OUTPUT
v_tot_salary:=v_tot_salary+v_salary;
END LOOP;
CLOSE c_emp;
DBMS_OUTPUT
END LOOP;
CLOSE c_dept;
END;
游標FOR循環
在大多數時候我們在設計程序的時候都遵循下面的步驟:
可以簡單的把這一類代碼稱為游標用於循環
FOR record_name IN
(corsor_name[(parameter[
| (query_difinition)
LOOP
statements
END LOOP;
下面我們用for循環重寫上面的例子:
DECALRE
CURSOR c_dept IS SELECT deptno
CURSOR c_emp (p_dept VARACHAR
SELECT ename
FROM emp
WHERE deptno=p_dept
ORDER BY ename
v_tot_salary EMP
BEGIN
FOR r_dept IN c_dept LOOP
DBMS_OUTPUT
v_tot_salary:=
FOR r_emp IN c_emp(r_dept
DBMS_OUTPUT
v_tot_salary:=v_tot_salary+v_salary;
END LOOP;
DBMS_OUTPUT
END LOOP;
END;
在游標FOR循環中使用查詢
在游標FOR循環中可以定義查詢
DECALRE
v_tot_salary EMP
BEGIN
FOR r_dept IN (SELECT deptno
DBMS_OUTPUT
v_tot_salary:=
FOR r_emp IN (SELECT ename
FROM emp
WHERE deptno=p_dept
ORDER BY ename) LOOP
DBMS_OUTPUT
v_tot_salary:=v_tot_salary+v_salary;
END LOOP;
DBMS_OUTPUT
END LOOP;
END;
游標中的子查詢
語法如下:
CURSOR C
WHERE deptno NOT IN (SELECT deptno
FROM dept
WHERE dname!=
可以看出與SQL中的子查詢沒有什麼區別
游標中的更新和刪除
在PL/SQL中依然可以使用UPDATE和DELETE語句更新或刪除數據行
UPDATE或DELETE語句中的WHERE CURRENT OF子串專門處理要執行UPDATE或DELETE操作的表中取出的最近的數據
語法:
FOR UPDATE [OF [schema
[nowait]
在多表查詢中
在UPDATE和DELETE中使用WHERE CURRENT OF子串的語法如下:
WHERE{CURRENT OF cursor_name|search_condition}
例:
DELCARE
CURSOR c
FROM emp
WHERE comm IS NULL
FOR UPDATE OF comm;
v_comm NUMBER(
BEGIN
FOR r
IF r
v_comm:=r
ELSEIF r
v_comm:=r
ELSEIF r
v_comm:=r
ELSE
v_comm:=r
END IF;
UPDATE emp;
SET comm=v_comm
WHERE CURRENT OF c
END LOOP;
END
From:http://tw.wingwit.com/Article/program/Oracle/201311/18863.html