从Oracle函数返回记录的标准方法是什么?

时间:2013-07-15 08:07:18

标签: oracle plsql procedure

对于我的问题,我真的避免使用“最好的”这个词,但它确实是最合适的词。

从函数返回记录的最佳(最有效)方法是什么?

目前我有类似的东西:

  FUNCTION myFunct(param1 VARCHAR2) RETURN SYS_REFCURSOR AS
    myCursor SYS_REFCURSOR;
  BEGIN
    OPEN myCursor FOR
    SELECT *
    FROM myTable
    WHERE field = param1;

    RETURN(myCursor);
  END myFunct;

我可以运行这个很好,但我正在阅读的其他内容(TABLE类型,隐式游标等)我真的很困惑什么是最合适的。

P.S。我从proc中调用它后如何循环遍历此光标?

编辑: 我已经读过,我只能通过游标ONCE(forums.oracle.com/thread/888365)进行迭代,但实际上我想多次循环内容。这是否意味着我选择使用关联数组?

1 个答案:

答案 0 :(得分:1)

create or replace 
PACKAGE example_pkg AS

    /*
    ** Record and nested table for "dual" table
    ** It is global, you can use it in other packages
    */
    TYPE g_dual_ntt IS TABLE OF SYS.DUAL%ROWTYPE;
    g_dual  g_dual_ntt;

    /*
    ** procedure is public. You may want to use it in different parts of your code
    */
    FUNCTION myFunct(param1 VARCHAR2) RETURN SYS_REFCURSOR;

    /*
    ** Example to work with a cursor
    */
    PROCEDURE example_prc;

END example_pkg;

create or replace 
PACKAGE BODY example_pkg AS

    FUNCTION myFunct(param1 VARCHAR2) RETURN SYS_REFCURSOR
    AS
        myCursor SYS_REFCURSOR;
    BEGIN
        OPEN myCursor FOR
            SELECT  dummy
            FROM    dual
            WHERE   dummy = param1;

        RETURN(myCursor);
    END myFunct;

    PROCEDURE example_prc
    AS
        myCursor SYS_REFCURSOR;
        l_dual   g_dual_ntt; /* With bulk collect there is no need to initialize the collection */
    BEGIN
        -- Open cursor
        myCursor := myFunct('X');
        -- Fetch from cursor  /  all at onece
        FETCH myCursor BULK COLLECT INTO l_dual;
        -- Close cursor
        CLOSE myCursor;

        DBMS_OUTPUT.PUT_LINE('Print: ');
        FOR indx IN 1..l_dual.COUNT LOOP
            DBMS_OUTPUT.PUT_LINE('element: ' || l_dual(indx).dummy );
        END LOOP;
    END example_prc;

END example_pkg;

EXECUTE example_pkg.example_prc();

/*
Print: 
element: X
*/

请看一下这个链接:http://www.oracle-base.com/articles/misc/using-ref-cursors-to-return-recordsets.php

您可能会发现它很有用......