在不同的代码块pl sql中填充varray的最佳方法

问题描述 投票:0回答:2

通常我填充这样的数组:

TYPE name_options IS VARRAY(6) OF VARCHAR2(300);
dd_name_options_c name_options;

dd_name_options_c := name_options(string1, string2, string3, string4);

但是如果我有两个生成字符串的块并且我想将所有字符串保存到一个数组怎么办:

-- Block 1
....
dd_name_options_c := name_options(string1, string2, string3, string4);
....
-- Block 2
....
dd_name_options_c := name_options(string5, string6);

所以,最后,数组将包含6个字符串:string1,string2,string3,string4,string5,string6

我怎样才能做到这一点?

oracle plsql user-defined-types
2个回答
2
投票

你可以使用extend

declare
  TYPE name_options IS VARRAY(6) OF VARCHAR2(300);
  dd_name_options_c name_options;

begin
  dd_name_options_c := name_options('a', 'b', 'c', 'd');

  dd_name_options_c.Extend(2);
  dd_name_options_c(5) := 'e';
  dd_name_options_c(6) := 'f';

  dbms_output.put_line(dd_name_options_c.count());
end;
/

2
投票

如果我有两个生成字符串的块并且我想将所有字符串保存到一个数组中该怎么办?

如果块是单独的程序单元或以其他方式断开连接,甚至可以以不同的顺序执行,则需要一些逻辑来判断目标阵列是否已经填充。一种解决方案是使用(私有)PL / SQL过程来管理它。

procedure populate_varray 
     ( p_tgt in out name_options
       , p_new in name_options)
is
   n pls_integer;
begin
   if p_tgt is null 
         or p_tgt.count() = 0 
   then
     p_tgt := p_new;
   elsif  p_new is not null 
         and p_new.count() > 0
   then 
     n := p_tgt.count();
     for idx in 1 .. p_new.count() loop
       p_tgt.extend();
       p_tgt(n + idx) := p_new(idx);
     end loop;
   end if;
end populate_varray;

注意:未经测试的代码,如果有错误请在下面评论:)

你会这样称呼它:

-- Block 1
....
populate_varray ( dd_name_options_c 
                  , name_options(string1, string2, string3, string4));
....
-- Block 2
....
populate_varray (dd_name_options_c  
                  , name_options(string5, string6) );
© www.soinside.com 2019 - 2024. All rights reserved.