Cursor的PL / SQL代码中的错误

时间:2016-05-15 22:40:58

标签: sql oracle plsql rdbms cursors

Declare 
      vStudent_id     grade.student_id%TYPE;
      vSection_id     grade.section_id%TYPE;
      vNumeric_grade  grade.numeric_grade%TYPE;

      CURSOR gradeCursor IS
             SELECT student_id,section_id,numeric_grade
             FROM grade
             WHERE student_id = 102
             ORDER by numeric_grade;
Begin
  Open gradeCursor;
  LOOP

    FETCH gradeCursor
            INTO vStudent_id,vSection_id,vNumeric_grade;
    EXIT WHEN gradeCursor%NOTFOUND;


    DBMS_OUTPUT.PUT_LINE('Student number: ' || vStudent_id );
    DBMS_OUTPUT.PUT_LINE('Section_id: ' || vSection_id );
    IF numeric_grade IS NOT NULL THEN
                    DBMS_OUTPUT.PUT_LINE('Numeric Grade: ' || vNumeric_grade );
    ELSE
                    DBMS_OUTPUT.PUT_LINE('Numeric Grade:  NULL' );
    END IF;
  END LOOP;
  IF gradeCursor%ISOPEN THEN CLOSE gradeCursor; END IF;

  EXCEPTION
    WHEN OTHERS THEN
          DBMS_OUTPUT.PUT_LINE('Error dected' );
          IF gradeCursor%ISOPEN THEN CLOSE gradeCursor; END IF;
END;

1 个答案:

答案 0 :(得分:0)

通过排除隐式游标和所有内容,可以轻松简化您的代码。您可以轻松使用FOR循环来满足您的要求。希望下面的代码有帮助。

DECLARE
  vStudent_id grade.student_id%TYPE;
  vSection_id grade.section_id%TYPE;
  vNumeric_grade grade.numeric_grade%TYPE;
BEGIN
  FOR I IN
  (SELECT student_id,
    section_id,
    numeric_grade
  FROM grade
  WHERE student_id = 102
  ORDER BY numeric_grade
  )
  LOOP
    DBMS_OUTPUT.PUT_LINE('Student number: ' || i.student_id);
    DBMS_OUTPUT.PUT_LINE('Section_id: ' || i.section_id);
    IF i.numeric_grade IS NOT NULL THEN
      DBMS_OUTPUT.PUT_LINE('Numeric Grade: ' || i.numeric_grade );
    ELSE
      DBMS_OUTPUT.PUT_LINE('Numeric Grade:  NULL' );
    END IF;
  END LOOP;
EXCEPTION
WHEN OTHERS THEN
  DBMS_OUTPUT.PUT_LINE('Error dected' );
END;