【问题标题】:PL/SQL Function - Bulk Collect into and Pipe RowPL/SQL 函数 - 批量收集到管道行
【发布时间】:2020-07-11 09:46:37
【问题描述】:

我是 PL/SQL 新手,对函数的输出值有疑问。

我想在函数中执行一条 SQL 语句并返回结果。该函数将使用以下命令执行:select * from table(mypkg.execute_query('1'));

我使用以下文章作为参考"Bulk Collect Into" and "Execute Immediate" in Oracle,但没有成功。

看来我使用了错误的数据类型。系统在以下行返回问题:PIPE Row(results)

create or replace package mypkg
as 
    type node is table of edges%ROWTYPE;
    function execute_query (startNode in varchar2) RETURN node PIPELINED;
end;


create or replace package body mypkg
as
   function execute_query(startNode in varchar2) RETURN node PIPELINED
    AS
        results node;
        my_query VARCHAR2(100);
        output VARCHAR2(1000);
        c sys_refcursor;
    BEGIN
        my_query := 'SELECT DISTINCT * FROM EDGES WHERE src='|| startNode;
        
        open c for my_query;
        loop
            fetch c bulk collect into results limit 100;
            exit when c%notfound;
                PIPE Row(results);
        end loop;
        close c;
    END;
end;

我用光标尝试了几个选项,但无法返回值。如果您知道如何使用 PIPELINED 以外的方式返回数据,请告诉我。

感谢您的支持!

【问题讨论】:

    标签: oracle plsql


    【解决方案1】:

    固定体:

    create or replace package body mypkg
    as
       function execute_query(startNode in varchar2) RETURN node PIPELINED
        AS
            results node;
            my_query VARCHAR2(100);
            output VARCHAR2(1000);
            c sys_refcursor;
        BEGIN -- don't use concatenation, it leads to sql injections:
            my_query := 'SELECT DISTINCT * FROM EDGES WHERE src=:startNode';
            -- use bind variables and bind them using cluase "using":
            open c for my_query using startNode;
            loop
                fetch c bulk collect into results limit 100;
                -- "results" is a collection, so you need to iterate it to pipe rows:
                for i in 1..results.count loop
                    PIPE Row(results(i));
                end loop;
                exit when c%notfound;
            end loop;
            close c;
        END;
    end;
    /
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-28
      • 1970-01-01
      • 2021-03-06
      • 1970-01-01
      • 2011-02-12
      • 1970-01-01
      • 2021-01-08
      • 1970-01-01
      相关资源
      最近更新 更多