Question

Hope you're doing well. I'm new to oracle PL/SQL and I'm trying to write a query just with the aim of practicing 'Cursor's . I have three tables with below structures :

Student:(Student_id , Student_name)
Course :(COURSE_NO , description)
Student_Course:(Student_id , Course_id , Nomreh)

Table Student_Course stores each student's mark in each course . the word 'Nomreh' is the Persian of Mark. I just want to know what wrong with my query is? Everything seems flawless! But I receive these errors :

ORA-01403:no data found
ORA-06512:at line 13

Here is my query :

DECLARE
  CURSOR C1 IS
        SELECT S.STUDENT_ID FROM STUDENT S;

        C1_REC               C1%ROWTYPE;
        V_STUDENT_FIRST_NAME STUDENT.STUDENT_NAME%TYPE;
        V_COURSE_DESCRIPTION COURSE.DESCRIPTION%TYPE;
        V_NOMRE              STUDENT_COURSE.NOMREH%TYPE;

  BEGIN
     FOR C1_REC IN C1 LOOP

        SELECT S.STUDENT_NAME, C.DESCRIPTION, SC.NOMREH
        INTO V_STUDENT_FIRST_NAME, V_COURSE_DESCRIPTION, V_NOMRE
        FROM STUDENT S
             INNER JOIN STUDENT_COURSE SC
        ON S.STUDENT_ID = SC.STUDENT_ID
             INNER JOIN COURSE C
        ON SC.COURSE_ID = C.COURSE_NO
        WHERE S.STUDENT_ID = C1_REC.STUDENT_ID;

  INSERT INTO TARGETTABLE
  (STUDENT_NAME, COURSE_NAME, NOMRE)
      VALUES
  (V_STUDENT_FIRST_NAME, V_COURSE_DESCRIPTION, V_NOMRE);
 END LOOP;
   COMMIT;
 END;

Thanks in advance

Was it helpful?

Solution

The SQL statement inside the loop may be fine, but it still does not return data.

SELECT ... INTO ... throws an error ORA-01403 when "no data found":

declare
  l_num number;
begin
  select 1 into l_num from dual where 1 = 2;
end;
/

ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 4

That code you wrote fails no only when the query does not return rows, it would also fail if the query returned multiple rows (a student attending multiple courses):

declare
  l_num number;
begin
  select 1 into l_num from dual connect by level <= 2;
end;
/

ERROR at line 1:
ORA-01422: exact fetch returns more than requested number of rows
ORA-06512: at line 4

Here is something that should work (just for the sake of this example):

DECLARE
  CURSOR C1 IS
        SELECT S.STUDENT_ID FROM STUDENT S;
        C1_REC               C1%ROWTYPE;
BEGIN
    FOR C1_REC IN C1 LOOP

       INSERT INTO TARGETTABLE
       (STUDENT_NAME, COURSE_NAME, NOMRE)
       SELECT S.STUDENT_NAME, C.DESCRIPTION, SC.NOMREH
       FROM STUDENT S
            INNER JOIN STUDENT_COURSE SC
       ON S.STUDENT_ID = SC.STUDENT_ID
            INNER JOIN COURSE C
       ON SC.COURSE_ID = C.COURSE_NO
       WHERE S.STUDENT_ID = C1_REC.STUDENT_ID;
END LOOP;
  COMMIT;
END; 
/
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top