Search code examples
oracleplsqloracle11g

Create var inside a for loop PLSQL ORACLE 11G


i have a function that puts a number in a var (var1). if var1 = 3 then create 3 new variables and assign a value for later send that values in an out type. I don't know how can i do, my code is something like this where "pos" acts like an INSTR() that i know its each 13 chars. And "newvar||var1" is because i want my vars names be newvar1, newvar2, newvar3, etc.:

FOR n IN 1..var1
LOOP
  pos          NUMBER(4):= 0;
  newvar||var1 NUMBER(3);
  newvar||var1 := SUBSTR(TO_NUMBER(numberInsideString), 1, 1+pos);
  pos := pos+13;
END LOOP;

My question is, how a person who really know PLSQL would do that, im learning PLSQL please help. thank you.


Solution

  • What you want to try to do suggests that you need a one dimensional array in order repeatedly to assign new values for each iteration within the loop. One of the types in OWA package such as vc_arr(composed of VARCHAR2 data type values) is handy to define an array.

    Coming to the code, you can start with moving the variables into the declaration section, and write such a simple code as a sample exercise

    SET serveroutput ON
    
    DECLARE
      pos                INT := 0;
      numberInsideString VARCHAR2(100):='as12df34sdg345apl8976gkh4f11öjhöh678u7jgvj';
      newvar             OWA.vc_arr;
    BEGIN
      FOR n IN 1..3
      LOOP    
        newvar(n) := SUBSTR(numberInsideString, 1, 1+pos);
        pos := pos+5;
        Dbms_Output.Put_Line(newvar(n));
      END LOOP;  
    END;
    /
    a
    as12df
    as12df34sdg