title: PL SQL Cursor For Loop: add up values in same variable and output the summed total
body: <p>I'm trying to calculate the GPA within a function that accepts a studentID as an input. My issue is that the variable <code>lv_gpa_calc</code> isn't adding to itself when the loop works through the cursor set. I added the <code>DBMS_OUTPUT.PUT_LINE</code> to make sure that it's working through the cursor set correctly and that prints to the screen the correct individual row values of what <code>lv_gpa_calc</code> should be, but when it gets returned in the function in a SQL block, it isn't adding all of those values together. Can you not set a variable to itself within a CURSOR FOR LOOP? </p>
  
  <p>Update: initializing the <code>lv_gpa_calc</code> fixed the problem where the variable value wasn't adding to itself. </p>
  
  <pre><code>CREATE OR REPLACE 
  FUNCTION CALCULATE_GPA 
  (p_studentID IN number)
  RETURN NUMBER
  IS
    CURSOR cur_gpa IS
        SELECT grade, grade_value, credit_hours
        FROM grade
        JOIN enrollment USING (Grade)
        JOIN section USING (term_code, subject_code, course_number, section)
        JOIN course USING (subject_code, course_number)
        WHERE student_ID = p_studentID;
  
    lv_gpa_calc NUMBER(4,2):=0;
  BEGIN
    FOR rec_gpa IN cur_gpa LOOP
    lv_gpa_calc:= lv_gpa_calc + ((rec_gpa.grade_value * rec_gpa.credit_hours)/rec_gpa.credit_hours);
    DBMS_OUTPUT.PUT_LINE(lv_gpa_calc);
    END LOOP;
    RETURN lv_gpa_calc;
  
  END CALCULATE_GPA;
  </code></pre>