如何使用循环将值添加到 VARRAY
How to add values to a VARRAY using a loop
我有一个 VARRAY,我想通过循环向这个 VARRAY 添加元素。这是我到目前为止尝试过的。
DECLARE
TYPE code_array_ IS VARRAY(26) OF VARCHAR2(6);
codes_ code_array_;
BEGIN
FOR i IN 1..26 LOOP
codes_(i) := dbms_random.string('U',6);
END LOOP;
END;
上面的代码给我一个错误
"ORA-06531: Reference to uninitialized collection"
如错误信息所述,您需要 initialise the collection variable:
...
BEGIN
codes_ := code_array_();
...
但是您还需要调整它的大小,或者每次在循环中使用一个扩展名:
FOR i IN 1..26 LOOP
codes_.extend;
...
或者在您开始之前进行一次性延期:
...
BEGIN
codes_ := code_array_();
...
codes_.extend(26);
FOR i IN 1..26 LOOP
...
您也可以使用 post-extend 大小来控制循环,再次保存硬编码 26:
DECLARE
TYPE code_array_ IS VARRAY(26) OF VARCHAR2(6);
codes_ code_array_;
BEGIN
codes_ := code_array_();
codes_.extend(26);
FOR i IN 1..codes_.count LOOP
codes_(i) := dbms_random.string('U',6);
END LOOP;
END;
/
PL/SQL procedure successfully completed.
在将值分配给集合变量的特定元素之前,您必须使用构造函数初始化 varray 并扩展它。
在 PLSQL 上下文中,最好使用关联集合。
declare
type code_array_ is varray(26) of varchar2(6);
codes_ code_array_ := code_array_();
begin
<<init_codes>> begin codes_.extend(26);
for i in codes_.first..codes_.last loop codes_(i) := dbms_random.string('U',6);
end loop; end init_codes;
end;
/
或者您可以使用 sql 来初始化整个集合,例如像这样:
declare
type code_array_ is varray(26) of varchar2(6);
codes_ code_array_;
begin
select dbms_random.string('U',6) bulk collect into codes_ from dual connect by level<=26;
end;
/
我有一个 VARRAY,我想通过循环向这个 VARRAY 添加元素。这是我到目前为止尝试过的。
DECLARE
TYPE code_array_ IS VARRAY(26) OF VARCHAR2(6);
codes_ code_array_;
BEGIN
FOR i IN 1..26 LOOP
codes_(i) := dbms_random.string('U',6);
END LOOP;
END;
上面的代码给我一个错误
"ORA-06531: Reference to uninitialized collection"
如错误信息所述,您需要 initialise the collection variable:
...
BEGIN
codes_ := code_array_();
...
但是您还需要调整它的大小,或者每次在循环中使用一个扩展名:
FOR i IN 1..26 LOOP
codes_.extend;
...
或者在您开始之前进行一次性延期:
...
BEGIN
codes_ := code_array_();
...
codes_.extend(26);
FOR i IN 1..26 LOOP
...
您也可以使用 post-extend 大小来控制循环,再次保存硬编码 26:
DECLARE
TYPE code_array_ IS VARRAY(26) OF VARCHAR2(6);
codes_ code_array_;
BEGIN
codes_ := code_array_();
codes_.extend(26);
FOR i IN 1..codes_.count LOOP
codes_(i) := dbms_random.string('U',6);
END LOOP;
END;
/
PL/SQL procedure successfully completed.
在将值分配给集合变量的特定元素之前,您必须使用构造函数初始化 varray 并扩展它。 在 PLSQL 上下文中,最好使用关联集合。
declare
type code_array_ is varray(26) of varchar2(6);
codes_ code_array_ := code_array_();
begin
<<init_codes>> begin codes_.extend(26);
for i in codes_.first..codes_.last loop codes_(i) := dbms_random.string('U',6);
end loop; end init_codes;
end;
/
或者您可以使用 sql 来初始化整个集合,例如像这样:
declare
type code_array_ is varray(26) of varchar2(6);
codes_ code_array_;
begin
select dbms_random.string('U',6) bulk collect into codes_ from dual connect by level<=26;
end;
/