结合2个VARRAYS Oracle PL / SQL

问题描述

我有一个返回代码数组(NUMBER)的函数

select GET_USER_OFFICE_CODES(10) FROM DUAL;
--output--
DB.OFFICE_CODES(3,4,5,6,7,8,9)

select GET_USER_OFFICE_CODES(2) FROM DUAL;    
--output--
DB.OFFICE_CODES(1,10,14,21)

一个函数中,我试图合并2个相同类型的数组。我收到错误消息“调用'MULTISET_UNION_ALL'时参数类型错误

create or replace function COMBINE_OFFICE_CODES(
  in_local_office_code NUMBER,in_regional_office_code NUMBER
)
RETURN OFFICE_CODES
IS
  local_office_codes OFFICE_CODES;
  regional_office_codes OFFICE_CODES;
  combined_office_codes OFFICE_CODES; 
Begin
  local_office_codes := GET_USER_OFFICE_CODES(in_local_office_code);
  regional_office_codes := GET_USER_OFFICE_CODES(in_regional_office_code);
  combined_office_codes := local_office_codes MULTISET UNION ALL regional_office_codes;

  RETURN combined_office_codes;
end

解决方法

您可以使用UNION ALL;

create type OFFICES_CODES is varray(100) of number;

declare
  local_office_codes OFFICES_CODES := OFFICES_CODES(1,2);
  regional_office_codes OFFICES_CODES := OFFICES_CODES(3,4);
  combined_office_codes OFFICES_CODES; 
Begin

  SELECT * BULK COLLECT INTO  combined_office_codes FROM  
  (select *from table(local_office_codes) 
    UNION ALL  
  select *from table(regional_office_codes));
 
 FOR i in 1..combined_office_codes.count loop
    DBMS_OUTPUT.PUT_LINE(combined_office_codes(i));
 end loop;
 
end;
/

陈述已处理。 1 2 3 4

************* EIDT *********

您还可以摆脱局部变量,直接使用函数。 试试这个:

create or replace type OFFICES_CODES is varray(100) of number;

create or replace function  get_office_codes (nNum number) return OFFICES_CODES
is
vRet offices_codes;
begin
    if nNum = 1 then
        vRet := offices_codes(1,4);
    else
        vRet := offices_codes(3,6);
    end if;
    return vRet;
end;
/


declare
  combined_office_codes OFFICES_CODES; 
Begin

  SELECT * BULK COLLECT INTO  combined_office_codes FROM  
  (select * from table(get_office_codes(1)) 
    UNION ALL  
  select *from table(get_office_codes(2))
  ORDER BY 1);
 
 FOR i in 1..combined_office_codes.count loop
    DBMS_OUTPUT.PUT_LINE(combined_office_codes(i));
 end loop;
 
end;
/