Search code examples
plsqlsql-updatecursoralter

Add new columns into an existing table and Update them using values from a cursor in PL/SQL


In the picture there is an example of the table I have and the table I need to create.

I have to calculate some values using the table Testing, then and add some new columns(Id2x and Id3x) to it and update these columns using the values I calculated. I found out that the problem is in trying to create the columns and them changing it. If I already had the columns id2x and id3x in my table i can update the table as long as I comment the line EXECUTE IMMEDIATE 'Alter table Testing add (id2X NUMBER, id3X NUMBER)';

Table to be updated using cursor

SET SERVEROUTPUT ON
DECLARE
  CURSOR cursorP IS
        SELECT id, (2*id) as id2X, (3*id)as id3X
        FROM Testing
        FOR UPDATE OF id2X, id3X;
BEGIN          
  EXECUTE IMMEDIATE 'Alter table Testing add (id2X NUMBER, id3X NUMBER)';

  FOR line IN cursorP LOOP
    UPDATE Testing 
    SET id2X = line.id2X,
        id3X = line.id3X
    WHERE current of cursorP;
  END LOOP;
END;

ERROR:

ORA-06550: line 10, column 33:
PL/SQL: ORA-00904: "ID3X": invalid identifier
ORA-06550: line 9, column5:
PL/SQL: SQL Statement ignored
06550. 00000 - "line %s, column %s:\n%s"
*Cause: Usually a PL/SQL compilation


Solution

  • If its just a one time execution block, just move the alter statement outside the block. try this

    SET SERVEROUTPUT ON
    Alter table Testing add (id2X NUMBER, id3X NUMBER);
    
    DECLARE
      CURSOR cursorP IS
            SELECT id, (2*id) as id2X, (3*id)as id3X
            FROM Testing
            FOR UPDATE OF id2X, id3X;
    BEGIN          
    
    
      FOR line IN cursorP LOOP
        UPDATE Testing 
        SET id2X = line.id2X,
            id3X = line.id3X
        WHERE current of cursorP;
      END LOOP;
    END;