示例 2:演示用 %TYPE 声明 Collection
使用 %TYPE 指定之前已声明的 collection 类型,改变 collection 定义,会根据元素数量和类型自动更新其他变量。
DECLARETYPE few_depts IS VARRAY(10) OF VARCHAR2(30);
TYPE many_depts IS VARRAY(100) OF VARCHAR2(64);
some_depts few_depts;
/* If the type of some_depts changes from few_depts to many_depts,
local_depts and global_depts will use the same type
when this block is recompiled */
local_depts some_depts%TYPE;
global_depts some_depts%TYPE;
BEGIN NULL;END;/
示例 3:演示声明一个 nested Table 作为存储过程的参数
声明 collection 为子程序的形参,把 collection 从一个子程序传递给另一个子程序。
CREATE PACKAGE personnel AS
TYPE staff_list IS TABLE OF employees.employee_id%TYPE;
PROCEDURE award_bonuses (empleos_buenos IN staff_list);
END personnel;/
CREATE PACKAGE BODY personnel AS
PROCEDURE award_bonuses (empleos_buenos staff_list) IS
BEGINFOR i IN empleos_buenos.FIRST..empleos_buenos.LAST
LOOP
UPDATE employees SET salary = salary + 100
WHERE employees.employee_id = empleos_buenos(i); END LOOP; END; END;/
若从包外部调用 personnel.award_bonuses,可以声明一个 personnel.staff_list 类型的变量,并把它作为参数传递。
DECLAREgood_employees personnel.staff_list;
BEGINgood_employees := personnel.staff_list(100, 103, 107);
personnel.award_bonuses (good_employees);
END;/
也可以在 RETURN 子句指定 collection 类型。
示例 4:演示用 %TYPE 和 %ROWTYPE 指定 collection 元素类型
若指定元素类型,则可用 %TYPE,提供一个变量或数据库列的数据类型(data type )。也可用 %ROWTYPE,提供游标或数据库表的行类型(row type)。
DECLARE-- Nested table type that can hold an arbitrary number-- of employee IDs.-- The element type is based on a column from the EMPLOYEES table. -- You need not know whether the ID is a number or a string.TYPE EmpList IS TABLE OF employees.employee_id%TYPE;
-- Declare a cursor to select a subset of columns.CURSOR c1 IS SELECT employee_id FROM employees;
-- Declare an Array type that can hold information-- about 10 employees.-- The element type is a record that contains all the same-- fields as the EMPLOYEES table.TYPE Senior_Salespeople IS VARRAY(10) OF employees%ROWTYPE;
-- Declare a cursor to select a subset of columns.CURSOR c2 IS SELECT first_name, last_name FROM employees;
-- Array type that can hold a list of names. The element type-- is a record that contains the same fields as the cursor-- (that is, first_name and last_name).TYPE NameList IS VARRAY(20) OF c2%ROWTYPE;
BEGIN NULL;END;/
示例 5:演示使用 RECORD 类型指定元素类型:Records 的 varray
DECLARE TYPE name_rec IS RECORD(first_name VARCHAR2(20),
last_name VARCHAR2(25));
TYPE names IS VARRAY(250) OF name_rec;
BEGIN NULL;END;/
示例 6:演示在 Collection 元素上加 NOT NULL 约束
DECLARETYPE EmpList IS TABLE OF employees.employee_id%TYPE NOT NULL;
v_employees EmpList := EmpList(100, 150, 160, 200);
BEGINv_employees(3) := NULL; -- assigning NULL raises an exception
END;/
