CURSOR使用

带参数的游标,和存储过程和函数相似,可以将参数传递给游标并在查询中使用。多用于在某种条件下打开游标的情况。

与存储过程不同的是,游标只能接受传递的值,而不能返回值。参数只定义数据类型,没有大小。

例子如下:

DECLARE
CURSOR c_dept IS SELECT * FROM DEPT ORDER BY DEPTNO;
CURSOR c_emp (p_dept VARCHAR2)
IS SELECT ENAME, SAL FROM EMP WHERE DEPTNO=p_dept ORDER BY ENAME;

r_dept DEPT%ROWTYPE;
v_ename EMP.ENAME%TYPE;
v_salary EMP.SAL%TYPE;
v_total_salary v_salary%TYPE;
BEGIN
OPEN c_dept;
LOOP
FETCH c_dept INTO r_dept;
EXIT WHEN c_dept%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('Department: ' || r_dept.DEPTNO || '-' || r_dept.DNAME);
v_total_salary := 0;
OPEN c_emp (r_dept.DEPTNO);
LOOP
FETCH c_emp INTO v_ename, v_salary;
EXIT WHEN c_emp%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('Name: ' || v_ename || ' Salary: ' || v_salary);
v_total_salary := v_total_salary + v_salary;
END LOOP;
CLOSE c_emp;
DBMS_OUTPUT.PUT_LINE('Total salary of depart: ' || v_total_salary);
END LOOP;
CLOSE c_dept;
END;

你可能感兴趣的:(Cursor)