开发者

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

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

Any suggestions ? Does the function need to be a pipeline function for it to be used in the for loop? Do I need to create a new type even though Im just returning numbers?

Thanks!

 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;


You would 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

You would then use the defined type like this:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜