How to set variables in a loop with oracle?

LazyCatIT picture LazyCatIT · Aug 9, 2013 · Viewed 19.3k times · Source

I have a loop and a variable v_rownum and I want to set value for it:

        FOR donvi_rows IN v_donvi
        LOOP
            DECLARE
               v_rownum number;
            SELECT r
            INTO v_rownum
            FROM
            (SELECT ROWNUM AS r, k.Id
            FROM don_vi k
            WHERE k.ParentId = 1 )
            WHERE Id = donvi_rows.Id;

        END LOOP;

But it throw a exception:

PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:

   begin function pragma procedure subtype type <an identifier>
   <a double-quoted delimited-identifier> current cursor delete
   exists prior
The symbol "begin" was substituted for "SELECT" to continue.

I'm currently studying Oracle. I don't know much about it. Please help me to resolve my problem.

Answer

Ed Gibbs picture Ed Gibbs · Aug 9, 2013

With Oracle you need to declare all your variables at the top of the block, before the BEGIN:

DECLARE
    ... variable declarations
BEGIN
    ... program logic
END;

Your code should go something like this:

DECLARE 
    v_rownum number;
    CURSOR v_donvi IS
      SELECT * FROM whatever;
    ... any other declarations
BEGIN
    FOR donvi_rows IN v_donvi
    LOOP
        SELECT r
          INTO v_rownum
          FROM (
            SELECT ROWNUM AS r, k.Id
            FROM don_vi k
            WHERE k.ParentId = 1
          )
          WHERE Id = donvi_rows.Id;
    END LOOP;
END;