簡體   English   中英

PostgreSQL:獲取函數返回的游標的內容

[英]Postgresql: Get content of cursors returned by function

一個psql函數(sp_some_function)返回2個游標:

create or replace function sp_some_function() RETURNS SETOF REFCURSOR
as 
$BODY$

  declare 

    c_one   refcursor                   := 'one'         ;
    c_two   refcursor                   := 'two'         ;

  begin

      open c_one   for
        select *
          from TABLE_1;

     return next c_one   ;

     open c_two   for
        select *
          from TABLE_2;

     return next c_two   ;

  return;
end
$BODY$
LANGUAGE PLPGSQL

我想查看兩個游標“包含”的數據。

為此,我編寫了以下腳本:

DO $$                    

BEGIN                    

 select sp_some_function(); 


 FETCH ALL IN "one";
 FETCH ALL IN "two";


END;                     
$$;   

運行腳本會導致以下錯誤消息:

ERROR:  "one" is not a known variable

我還嘗試了以下方法:

DO $$                    

BEGIN                    

 select sp_some_function(); 


 FETCH ALL IN c_one;
 FETCH ALL IN c_two;


END;                     
$$;   

這導致以下錯誤消息:

ERROR:  c_one is not a known variable

最后,我嘗試了以下方法:

create or replace function sp_some_function() RETURNS SETOF REFCURSOR
as 
$BODY$

  declare 

    c_one   refcursor                   := 'one'         ;
    c_two   refcursor                   := 'two'         ;

  begin

      open c_one   for
        select *
          from TABLE_1;

     FETCH ALL IN c_one;

     return next c_one   ;

     open c_two   for
        select *
          from TABLE_2;



     FETCH ALL IN c_two;  

     return next c_two   ;

  return;
end
$BODY$
LANGUAGE PLPGSQL

這也不起作用。

...如何獲取兩個游標的內容?

您的PL / pgSQL代碼錯誤。

在PL / pgSQL中,不能在沒有INTO情況下使用SELECT

對您來說最好的事情是執行以下操作(未經測試):

DECLARE
   c refcursor;
   a_row record;
BEGIN
   FOR c IN
      SELECT sp_some_function()
   LOOP
      LOOP
         FETCH c INTO a_row;
         EXIT IF NOT FOUND;
         /* do something with the result row */
      END LOOP;
   END LOOP;
END;

請按照以下方法獲取輸出

執行以下功能

BEGIN;        -- begin Transaction             

 select sp_some_function(); 

在這里,您將獲得refcusor值副本,然后從中獲取數據..例如:

 FETCH ALL IN "refcursor_value1";  -- Execute it seperately to see the result
 FETCH ALL IN "refcursor_value2";  -- Execute it seperately to see the result


END;  -- end Transaction            

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM