简体   繁体   中英

Output multiple rows of data from cursor using if statement PL/SQL

I am trying to output multiple rows of data from a table called 'student' using pl/sql. I am able to output the first row of data but that is all. I am familiar with loop procedures in other programming languages but am new to pl/sql here is what I have:

 DECLARE
   variable_Score Number;
   variable_LetterGrade Char(1);
   name char(10);
cursor studentPtr is SELECT name, grade from STUDENT;
BEGIN
   open studentPtr;
   LOOP
   fetch studentPtr into name, variable_Score;
   IF variable_Score >= 90 THEN
        variable_LetterGrade := 'A';
   ELSIF variable_Score >= 80 THEN
        variable_LetterGrade := 'B';
   ELSIF variable_Score >= 70 THEN
       variable_LetterGrade := 'C';
  ELSIF variable_Score >= 60 THEN
       variable_LetterGrade := 'D';
  ELSE
       variable_LetterGrade := 'F';
  END IF;
  DBMS_OUTPUT.PUT_LINE('Hello '||name||', you receive a  '||variable_LetterGrade||' for the class');
  EXIT;
  END LOOP;
  END;
  /

The output is :

Hello Joe , you receive a B for the class

This is just the first row from the student table though, there is three more rows of data I would like to output.

Problem is with the EXIT statement. A bare exit statement skips the loop and comes out displaying the row from first fetch .

So, remove the EXIT; before END LOOP and include an EXIT statement like this after your fetch .

  ..
  fetch studentPtr into name, variable_Score;
  EXIT WHEN studentPtr%NOTFOUND;
  ..
  ..

%NOTFOUND is a cursor attribute and becomes true when all rows are fetched. what the statement does is that it skips the loop only when no rows could be fetched from the cursor .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM