Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set variables in a loop with oracle?

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.

like image 334
LazyCatIT Avatar asked Jan 12 '23 16:01

LazyCatIT


1 Answers

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;
like image 158
Ed Gibbs Avatar answered Jan 18 '23 08:01

Ed Gibbs