Search code examples
oracle-databaseplsqlcursororacle-sqldeveloper

Need help understanding Cursor for loop


I am trying to write a code for every stock value that is $75 or more add a "*" in the STK_FLAG column. my error repots are: Error report -

ORA-06550: line 15, column 21: PLS-00201: identifier 'STK_FLG' must be declared ORA-06550: line 15, column 5: PL/SQL: SQL Statement ignored ORA-06550: line 23, column 7: PL/SQL: ORA-00904: "STK_FLG": invalid identifier ORA-06550: line 17, column 5: PL/SQL: SQL Statement ignored 06550. 00000 - "line %s, column %s:\n%s" *Cause: Usually a PL/SQL compilation error. *Action:

Blockquote

SET SERVEROUTPUT ON

DECLARE

CURSOR CURR
   IS
     SELECT STK_FLAG
     FROM MM_MOVIE
     WHERE MOVIE_VALUE * MOVIE_QTY >= 75
     FOR UPDATE;
BEGIN

OPEN CURR;
   
  LOOP

    FETCH CURR INTO STK_FLG;

    UPDATE

      MM_MOVIE

    SET

      STK_FLG= '*'

    WHERE

      CURRENT OF CURR;

    EXIT

  WHEN CURR%notfound;

  END LOOP;

  Commit;

   CLOSE CURR;
END;
/

Solution

  • You didn't declare a cursor variable (so there's nowhere you can put values returned by the cursor). Don't name it as column name; use a prefix, such as v_ or l_ or whichever you want.

    Furthermore, in UPDATE you referenced a non-existent column. Cursor suggests its name is stk_flag, not stk_flg

    Therefore, code that might be OK is

    DECLARE
       CURSOR curr IS
          SELECT stk_flag
            FROM mm_movie
           WHERE movie_value * movie_qty >= 75
          FOR UPDATE;
    
       l_stk_flag  mm_movie.stk_flag%TYPE;  --> this
    BEGIN
       OPEN curr;
    
       LOOP
          FETCH curr INTO l_stk_flag;
    
          EXIT WHEN curr%NOTFOUND;
    
          UPDATE mm_movie
             SET stk_flag = '*'             --> this
           WHERE CURRENT OF curr;
       END LOOP;
    
       COMMIT;
    
       CLOSE curr;
    END;
    /