Oracle

需要幫助確定如何使用 table() 子句和自定義數據類型使函式可選擇

  • February 3, 2021

我希望能夠執行以下程式碼來選擇記錄:

所需的語法

select * from table(my_new_package.get_data(123))

我已成功創建可編譯的程式碼,但無法使用上述語法檢索數據。誰能確定我如何更新它以確保上述查詢能夠正常執行。

這是目前程式碼:

包裝規格

create or replace package my_new_package is

 -- Types
 -------------
 type my_data_type is record (
     myfield1          VARCHAR2(10)
     ,myfield2         VARCHAR2(10)
   );
   
  type my_data_type_TABLE is table of my_data_type index by binary_integer;

  -- Functions
  -------------
  FUNCTION get_data(i_id_number varchar2) return my_data_type_table;

end my_new_package;

包體

create or replace package body my_new_package is

 function get_data(i_id_number varchar2) return my_data_type_table IS  
   current_row my_data_type;
   all_rows my_data_type_table;
   n integer;

   -- Will update the cursor to pull real data
   cursor cur is
     select '1' myfield1, '10' myfield2 from dual
     union all
     select '2' myfield1, '20' myfield2 from dual
   ;
 BEGIN    
   n := 0;
   for rec in cur LOOP
     n := n+ 1;
     current_row := rec;
     -- do some things to current row

     -- Add modified current row
     all_rows(n) := current_row;
   END LOOP;
   
   return all_rows;
 END;


end my_new_package;

上面的程式碼可以編譯,但我無法使用所需的語法從數據中進行選擇。

無論如何,在自定義類型僅嵌入包級別而不是在數據庫級別創建的情況下,是否可以這樣做?

這將適用於 Oracle 12(和 Oracle 19)。

您需要將函式定義為流水線。以下適用於 19c。

標頭:

create or replace package my_new_package is

 -- Types
 -------------
 type my_data_type is record (
     myfield1          VARCHAR2(10)
     ,myfield2         VARCHAR2(10)
   );
   
  type my_data_type_TABLE is table of my_data_type;

  -- Functions
  -------------
  FUNCTION get_data(i_id_number varchar2) return my_data_type_table pipelined;

end my_new_package;
/

包體:

create or replace package body my_new_package is

 function get_data(i_id_number varchar2) return my_data_type_table pipelined IS  
   current_row my_data_type;
   all_rows my_data_type_table;
   n integer;

   -- Will update the cursor to pull real data
   cursor cur is
     select '1' myfield1, '10' myfield2 from dual
     union all
     select '2' myfield1, '20' myfield2 from dual
   ;
 BEGIN    
   n := 0;
   for rec in cur LOOP
     n := n+ 1;
     pipe row(rec);
   END LOOP;
   
 END;


end my_new_package;
/

測試:

select * from table(my_new_package.get_data('A'));

MYFIELD1   MYFIELD2  
---------- ----------
1          10        
2          20  

引用自:https://dba.stackexchange.com/questions/284653