ORA-01001: 使用 'for' 循环的查询中的无效游标

use*_*446 1 oracle plsql

我正在尝试使用游标编写一个简单的查询,但是我不断收到这个臭名昭著的“无效游标”错误。这是我的代码。

DECLARE
    v_deptno NUMBER := 10;
    c_last_name employees.last_name%TYPE;
    c_salary employees.salary%TYPE;
    c_manager_id employees.salary%TYPE;
    CURSOR c_emp_cursor IS
        SELECT last_name, salary, manager_id FROM employees
        WHERE department_id = v_deptno;
BEGIN
   --OPEN c_emp_cursor;
-- commented out because for loop opens the cursor automatically
    FOR employee IN c_emp_cursor
    LOOP
        FETCH c_emp_cursor INTO c_last_name, c_salary, c_manager_id;
            EXIT WHEN c_emp_cursor%NOTFOUND;
            IF c_salary < 5000 THEN
                IF c_manager_id = 101 OR c_manager_id = 124 THEN
                    dbms_output.put_line(c_last_name || 'due for a raise.');
                ELSE
                    dbms_output.put_line(c_last_name || ' not due for a raise.');
                END IF;
            END IF;
    END LOOP;
    --CLOSE c_emp_cursor;
END;
Run Code Online (Sandbox Code Playgroud)

什么可能是错的,对此的解决方案是什么?我已经尝试为类似的问题应用可能的解决方案,但没有一个真正符合我的问题。

Lit*_*oot 5

当你注释掉OPENCLOSE,你应该删除FETCH,并EXIT为好,出于同样的原因。此外,现在您在FOR语句中有一个游标变量,所以 - 使用它。像这样的东西:

BEGIN
    FOR employee IN c_emp_cursor
    LOOP
            IF employee.salary < 5000 THEN
                IF employee.manager_id = 101 OR employee.manager_id = 124 THEN
                    dbms_output.put_line(employee.last_name || 'due for a raise.');
                ELSE
                    dbms_output.put_line(employee.last_name || ' not due for a raise.');
                END IF;
            END IF;
    END LOOP;
END;
Run Code Online (Sandbox Code Playgroud)