声明时VARRAY中的Oracle PL / SQL默认值

时间:2016-08-08 08:44:26

标签: arrays oracle

在声明以下代码行时元素的初始值是什么

{{1}}

我想知道存储在列表元素中的默认值。

1 个答案:

答案 0 :(得分:3)

你似乎误解了how VARRAYs work。当您将类型声明为VARRAY(100)时,您指定的类型可以包含的元素的最大数量,而不是 包含的元素数量。

在您的示例中,您是initialising the collection with no arguments

  

如果参数列表为空,则构造函数返回一个空集合。

所以收藏是空的;它有零元素(最大值为100);并且firstlast方法返回null,因为它们对于空集合是未知/无意义的。

使用extend向数组添加元素时,新元素也为空,直到为它们赋值。

为了说明@Mottor在评论中描述的行为,您可以使用匿名块来操作数组并查看每个阶段的样子:

set serveroutput on
declare
  type t_array is varray(100) of number;
  l_array t_array;

  procedure show_array_info(p_step pls_integer) is
  begin
    dbms_output.put('Step ' || p_step || ': ');
    if l_array is null then
      dbms_output.put_line('array has not been intialised');
      return;
    end if;
    dbms_output.put_line('count ' || l_array.count
      || ' first ' || nvl(to_char(l_array.first), '(null)')
      || ' last ' || nvl(to_char(l_array.last), '(null)'));
    if l_array.count = 0 then
      return;
    end if;
    for i in l_array.first..l_array.last loop
      dbms_output.put_line('  element ' || i || ': '
        || nvl(to_char(l_array(i)), '(null)'));
    end loop;
  end show_array_info;
begin
  -- array has been declared buyt not initialised
  show_array_info(1);
  -- initialisae array as empty
  l_array := t_array();
  show_array_info(2);
  -- increase number of elements by default 1; element is null
  l_array.extend;
  show_array_info(3);
  -- set value for last element
  l_array(l_array.count) := 42;
  show_array_info(4);
  -- increase number of elements by 3; new elements are null
  l_array.extend(3);
  show_array_info(5);
  -- set value for last element; others remain null
  l_array(l_array.count) := 17;
  show_array_info(6);
  -- remove last two elements; other two remain
  l_array.trim(2);
  show_array_info(7);
  -- remove all elements, leaving array empty
  l_array.trim(l_array.count);
  show_array_info(8);
--  l_array.extend(97);
end;
/

产生:

PL/SQL procedure successfully completed.

Step 1: array has not been intialised
Step 2: count 0 first (null) last (null)
Step 3: count 1 first 1 last 1
  element 1: (null)
Step 4: count 1 first 1 last 1
  element 1: 42
Step 5: count 4 first 1 last 4
  element 1: 42
  element 2: (null)
  element 3: (null)
  element 4: (null)
Step 6: count 4 first 1 last 4
  element 1: 42
  element 2: (null)
  element 3: (null)
  element 4: 17
Step 7: count 2 first 1 last 2
  element 1: 42
  element 2: (null)
Step 8: count 0 first (null) last (null)

如果您在集合为空时尝试引用第一个元素 - 或者更常见的是,任何使用大于当前计数的数字的元素 - 您将收到错误ORA-06533: Subscript beyond count。如果您尝试将集合扩展到超出声明的限制,那么您将获得ORA-06532: Subscript outside of limit