How to return a set of NUMBERS from a function in PLSQL and then use it in FOR LOOP?

I wanted to have a function in PLSQL that would return a set of numbers, and then there would be a for loop that would iterate over this data set and do something with it.

Any suggestions? Should a function be a pipeline function to use it in a for loop? Do I need to create a new type, although Im just returning numbers?

Thank!

 CREATE OR REPLACE PACKAGE BODY someBody AS

      FUNCTION getListOfNumbers RETURN someList IS -- what type do I return ??
      BEGIN
        RETURN SELECT SID FROM V$SESSION;  -- Not sure what do here ??
      END;

      PROCEDURE soSomeStuff IS
      BEGIN
        FOR rec IN(getListOfNumbers)  -- how do I select from the function?
        LOOP
          dbms_output.put_line(rec);
        END LOOP;
      END;
  END;
+2
source share
1 answer

You will need to declare a collection type :

SQL> CREATE OR REPLACE PACKAGE my_package AS
  2  
  3     TYPE someList IS TABLE OF NUMBER INDEX BY BINARY_INTEGER;
  4  
  5     FUNCTION getListOfNumbers RETURN someList;
  6     PROCEDURE soSomeStuff;
  7  
  8  END my_package;
  9  /

Package created

Then you would use a specific type as follows:

SQL> CREATE OR REPLACE PACKAGE BODY my_package AS
  2  
  3     FUNCTION getListOfNumbers RETURN someList IS
  4        l_list someList;
  5     BEGIN
  6        SELECT SID BULK COLLECT INTO l_list FROM V$SESSION;
  7        RETURN l_list;
  8     END;
  9  
 10     PROCEDURE soSomeStuff IS
 11        l_list someList;
 12     BEGIN
 13        l_list := getListOfNumbers;
 14        FOR i IN 1..l_list.count LOOP
 15           dbms_output.put_line(l_list(i));
 16        END LOOP;
 17     END;
 18  
 19  END my_package;
 20  /

Package body created

SQL> exec my_package.soSomeStuff;

284
285
287
288
[...]
PL/SQL procedure successfully completed
+5
source

All Articles