Oracle - 如何将记录添加到相同类型的集合(多集联合)

Oracle - How to add a Record to a Collection of the same Type (Multiset Union)

我已经使用 MULTISET UNION 将一个集合加载到另一个相同类型的集合中,但是我现在正在使用 Records 并想添加一个 记录到相同类型的集合。无论出于何种原因,我只是想不出合适的语法或简单的正确方法来执行此操作,因为 MULTISET UNION 似乎无法像我习惯使用 Collections 的方式那样很好地使用 Records。

我在最后添加了这段代码如何工作的总结(无论如何都应该工作)。

Screenshot and Code Below

LINE 44: c_los_ms_tbl_ret := c_los_ms_tbl_ret MULTISET UNION los_ms_row;

DECLARE  

  TYPE t_los_ms_rec IS RECORD(
      appt_id NUMBER DEFAULT NULL,
      appt_name VARCHAR(300) DEFAULT NULL,
      tot_units NUMBER DEFAULT 0,
      new_rentals NUMBER DEFAULT 0,
      term_rentals NUMBER DEFAULT 0,
      avg_los_all NUMBER DEFAULT 0
  );

  TYPE t_los_ms_tbl IS TABLE OF t_los_ms_rec;

  /* Two collections based on Table Type of Record t_los_ms_rec */
  c_los_ms_tbl_ret  t_los_ms_tbl  :=  t_los_ms_tbl();  
  c_los_ms_tbl      t_los_ms_tbl  :=  t_los_ms_tbl();  

  FUNCTION los_func(p_appt_ids IN VARCHAR) RETURN t_los_ms_tbl
  IS
        los_ms_row  t_los_ms_rec; /* Declare Row based on Record Type */

  BEGIN
    /* Outer loop: iterate through all user selected appartments. */
    FOR los IN 
    (
      SELECT 1001 AS appt_id, 45 AS tot_units, 10 AS new_rentals, 3 AS term_rentals, 'Building1' AS appt_name
        FROM dual UNION ALL
      SELECT 1002 AS appt_id, 37 AS tot_units, 6  AS new_rentals, 4 AS term_rentals, 'Building2' AS appt_name
        FROM duaL
    )
    LOOP      
      /* Set Row Fields to the Data being returned by Outer Loop.  Fake Table data from dual. */
      los_ms_row.appt_name    := los.appt_name;      
      los_ms_row.appt_id      := los.appt_id;
      los_ms_row.new_rentals  := los.new_rentals;
      los_ms_row.term_rentals := los.term_rentals;
      los_ms_row.tot_units    := los.tot_units;
      los_ms_row.avg_los_all  := 45; /* Made up Number */

      /* Output Apartment Name for testing */
      dbms_output.put_line('Apartment Name' || los_ms_row.appt_name);

      /* Save Row Data into Collection */ /* HOW DO I POPULATE COLLECTION WITH A RECORD */
      c_los_ms_tbl_ret  := c_los_ms_tbl_ret MULTISET UNION los_ms_row;

    END LOOP;

    RETURN c_los_ms_tbl_ret; /* Return Populated Collection */

  END los_func;  

BEGIN  
  /* Call Function and Store Returned Collection into a collection of same type */
  c_los_ms_tbl  :=  los_func(p_appt_ids => '1001,1002');

  FOR r IN c_los_ms_tbl.FIRST .. c_los_ms_tbl.LAST
  LOOP
    dbms_output.put_line(c_los_ms_tbl(r).avg_los_all);
  END LOOP;

END;

Summary

Error report -

ORA-06550:第 44 行,第 32 列: PLS-00306: 调用 'MULTISET_UNION_ALL'

时参数的数量或类型错误

MULTISET UNION 用于从两个嵌套的 table 中创建一个嵌套的 table。您正在尝试使用 MULTISET UNION 将嵌套的 table 和单个记录连接在一起。

有两种方法可以解决此问题:

  1. 从单个记录中创建一个元素 table:

        c_los_ms_tbl_ret  := c_los_ms_tbl_ret MULTISET UNION t_los_ms_tbl(los_ms_row);
    
  2. 放弃使用 MULTISET UNION,只需将新记录附加到 table:

        c_los_ms_tbl_ret.EXTEND(1);
        c_los_ms_tbl_ret(c_los_ms_tbl_ret.COUNT) := los_ms_row;