初始化和引用 Collection
初始化时,一个 nested table 或 varray 会自动为 null。collection 本身为 null,它没有元素。若初始化一个 nested table 或 varray,可以使用系统预定义的构造函数,该构造函数与 collection 类型名同名,通过传递给它的元素构造 collection。
必须显示为 nested table 和 varray 变量调用构造函数。而 associative array 则不需要这样。
示例 7:演示构造 nested table
DECLARETYPE dnames_tab IS TABLE OF VARCHAR2(30);
dept_names dnames_tab;
BEGINdept_names := dnames_tab('Shipping','Sales','Finance','Payroll');
END;/
nested table 没有声明大小,可以在构造函数放很多元素。
示例 8:演示构造 varray
DECLARE-- In the varray, put an upper limit on the number of elementsTYPE dnames_var IS VARRAY(20) OF VARCHAR2(30);
dept_names dnames_var;
BEGIN-- Because dnames is declared as VARRAY(20),-- you can put up to 10 elements in the constructordept_names := dnames_var('Shipping','Sales','Finance','Payroll');
END;/
示例 9:演示 Collection 构造函数包含 Null 元素
DECLARETYPE dnames_tab IS TABLE OF VARCHAR2(30);
dept_names dnames_tab;
TYPE dnamesNoNulls_type IS TABLE OF VARCHAR2(30) NOT NULL;
BEGINdept_names := dnames_tab('Shipping', NULL,'Finance', NULL);
-- If dept_names were of type dnamesNoNulls_type,-- you could not include null values in the constructorEND;/
示例 10:演示 Collection 声明和构造相结合
DECLARETYPE dnames_tab IS TABLE OF VARCHAR2(30);
dept_names dnames_tab :=
dnames_tab('Shipping','Sales','Finance','Payroll');
BEGIN NULL;END;/
示例 11:演示无参数的 varray 构造函数,会得到一个空的,而不是 null 的 collection
DECLARETYPE dnames_var IS VARRAY(20) OF VARCHAR2(30);
dept_names dnames_var;
BEGINIF dept_names IS NULL THEN
DBMS_OUTPUT.PUT_LINE
('Before initialization, the varray is null.');-- While the varray is null, you cannot check its COUNT attribute.-- DBMS_OUTPUT.PUT_LINE-- ('It has ' || dept_names.COUNT || ' elements.'); ELSEDBMS_OUTPUT.PUT_LINE
('Before initialization, the varray is not null.');END IF;
dept_names := dnames_var(); -- initialize empty varray IF dept_names IS NULL THEN
DBMS_OUTPUT.PUT_LINE
('After initialization, the varray is null.'); ELSEDBMS_OUTPUT.PUT_LINE
('After initialization, the varray is not null.');DBMS_OUTPUT.PUT_LINE
('It has ' || dept_names.COUNT || ' elements.');
END IF;
END;/
