循环的游标..没有使用open,fetch,close的原因

时间:2014-02-12 09:05:27

标签: oracle plsql

嗨我这里有两组代码

1

DECLARE
    CURSOR C_EMP IS SELECT * FROM EMP;
    TEMP EMP%ROWTYPE;

BEGIN

OPEN C_EMP;
    FOR TEMP IN C_EMP 
    LOOP
        FETCH C_EMP INTO TEMP;
        UPDATE EMP SET NAME = 'Great' where id = 1;

        DBMS_OUTPUT.PUT_LINE('EMP ID IS '|| TEMP.ID);
        DBMS_OUTPUT.PUT_LINE('EMP NAME IS '||TEMP.NAME);
        DBMS_OUTPUT.PUT_LINE('EMP SALARY IS '||TEMP.SALARY);
    END LOOP;
CLOSE C_EMP;    
END;

2

DECLARE
    CURSOR C_EMP IS SELECT * FROM EMP;
    --TEMP EMP%ROWTYPE;

BEGIN

--OPEN C_EMP;
    FOR TEMP IN C_EMP 
    LOOP
        --FETCH C_EMP INTO TEMP;
        UPDATE EMP SET NAME = 'Great' where id = 1;

        DBMS_OUTPUT.PUT_LINE('EMP ID IS '|| TEMP.ID);
        DBMS_OUTPUT.PUT_LINE('EMP NAME IS '||TEMP.NAME);
        DBMS_OUTPUT.PUT_LINE('EMP SALARY IS '||TEMP.SALARY);
    END LOOP;
--CLOSE C_EMP;  
END;

在第二个,如果我删除open,fetch,close代码工作正常。但是第一个代码是抛出错误游标已经打开。  这是什么原因?

1 个答案:

答案 0 :(得分:0)

FOR LOOP使用隐式游标,因此您无需打开,关闭和从游标中获取:

FOR temp IN (SELECT * FROM emp) LOOP
   -- refer to temp inside this loop
END LOOP;

就是你需要做的......