如何将ref_cursor提取到Oracle的WITH CLAUSE中

时间:2017-08-03 19:22:09

标签: oracle plsql

是否可以在ORACLE WITH CLAUSE中使用ref_cursor。例如,我有以下场景。首先,我有一个返回ref_cursor

的过程
PROCEDURE p_return_cursor(p_id IN NUMBER, io_cursor OUT t_cursor) 
AS
BEGIN
  OPEN io_cursor FOR
    SELECT col1, col2 
      FROM Table1 t 
     WHERE t.id = p_id;
END;

其次,我有另一个程序可以调用p_return_cursor:

PROCEDURE p_test(p_cid IN NUMBER)
AS
  l_cursor t_cursor;
  l_rec Table1%ROWTYPE;
BEGIN
  p_return_cursor(p_id => p_cid, io_cursor => l_cursor);
  -- CODE GOES HERE
...

现在,我的问题是,我可以使用游标使用Oracle的WITH CLAUSE制作临时表吗?类似的东西:

...
  WITH data AS (
    LOOP
      FETCH l_cursor INTO l_rec;
      EXIT WHEN l_cursor%NOTFOUND;
        SELECT l_rec.col1, l_rec.col2 FROM DUAL;
    END LOOP;
    CLOSE l_cursor;
    )

1 个答案:

答案 0 :(得分:2)

你不能直接这样做。但是,您可以将BULK COLLECT光标放入PL / SQL表变量中,并在WITH子句中使用

如果游标包含很多行,请注意内存使用情况。

完整示例:

CREATE TABLE table1 ( col1 NUMBER, col2 NUMBER );

INSERT INTO table1 ( col1, col2 ) SELECT rownum, 100+rownum FROM DUAL CONNECT BY ROWNUM <= 15;

COMMIT;

CREATE OR REPLACE PACKAGE se_example AS

  TYPE t_cursor IS REF CURSOR
    RETURN table1%ROWTYPE;

  TYPE l_rec_tab IS TABLE OF table1%ROWTYPE;


  PROCEDURE p_test (p_cid IN NUMBER);
END se_example;



CREATE OR REPLACE PACKAGE BODY se_example AS
  -- private
  PROCEDURE p_return_cursor (p_id IN NUMBER, io_cursor OUT t_cursor) AS
  BEGIN
    OPEN io_cursor FOR
      SELECT col1,
             col2
      FROM   table1 t; 
      --WHERE  t.id = p_id;  -- I didn't put "id" column in my sample table, sorry...
  END p_return_cursor;

  PROCEDURE p_test (p_cid IN NUMBER) IS
    l_cursor   t_cursor;
    l_tab      l_rec_tab;
    l_dummy    NUMBER;
  BEGIN
    p_return_cursor (p_id => p_cid, io_cursor => l_cursor);

    FETCH l_cursor BULK   COLLECT INTO l_tab;

  -- *** instead of this    

  --  WITH data AS (
  --    LOOP
  --      FETCH l_cursor INTO l_rec;
  --      EXIT WHEN l_cursor%NOTFOUND;
  --        SELECT l_rec.col1, l_rec.col2 FROM DUAL;
  --    END LOOP;
  --    CLOSE l_cursor;
  --    )
  --    '
  --

  -- *** do this    

    WITH data AS 
      ( SELECT col1, col2 FROM TABLE(l_tab) )
    SELECT sum(col1 * col2) INTO l_dummy
    FROM data;

    dbms_output.put_line('result is ' || l_dummy);

  END p_test;
END se_example;


begin
  se_example.p_test(100);
end;