金仓数据库KingbaseES PLSQL关联数组
关键字:
集合类型、关联数组、人大金仓
什么是关联数组
关联数组是PL/SQL中一种特殊的数据类型,它可以将单个的键与值关联起来。每个键值对都被存储在关联数组中,通过键来访问对应的值。关联数组可以看做是一种类似于字典的数据结构,在许多情况下都可以简化编程过程。
语法:
TYPE <plsql_table_type_name> IS TABLE OF <data_type>
INDEX BY BINARY_INTEGER;
索引的数据类型可以是字符串类型(VARCHAR2、VARCHAR、STRING 或 LONG)或 PLS_INTEGER。其中数据是按索引排序顺序存储的,而不是按创建顺序存储的。
与数据库表一样,关联数组在填充之前为空(但不为NULL),可以容纳不定量的元素,您可以在不知道其位置的情况下访问这些元素。
关联数组的使用示例
1. 以字符串为索引的关联数组
示例:
\set SQLTERM /
DECLARE
-- 声明一个以字符串为索引的关联数组
TYPE ass_type IS TABLE OF INT -- 数组类型
INDEX BY VARCHAR2(64); -- 数组索引
age ass_type; -- 数组变量
i VARCHAR2(64); -- 字符串变量
BEGIN
-- 和map相同,我们可以通过键值对的方式向关联数组中添加元素
age('zs') := 25;
age('ls') := 30;
age('ww') := 40;
-- 将键值对中的值进行修改:
age('zs') := 26;
-- 按顺序打印关联数组中的值:
i := age.FIRST; -- 获取数组中的第一个元素
WHILE i IS NOT NULL LOOP
RAISE NOTICE '% is % years old', i, age(i);
i := age.NEXT(i); -- 获取数组中的下一个元素
END LOOP;
END;
/
执行结果:
NOTICE: ls is 30 years old
NOTICE: ww is 40 years old
NOTICE: zs is 26 years old
2. 以 PLS_INTEGER 为索引的关联数组
示例:
\set SQLTERM /
DECLARE
TYPE area_of_circle IS TABLE OF NUMBER INDEX BY PLS_INTEGER; -- 声明一个以PLS_INTEGER为索引的关联数组
s area_of_circle; -- 声明关联数组变量
num INT = 3;
BEGIN
FOR i IN 1..num LOOP --循环向关联数组中赋值
s(i) := 2 * 3.14 * i * i;
END LOOP;
for i in 1..num LOOP -- 循环输出关联数组中的值
RAISE NOTICE 's(%) = %', i, s(i);
END LOOP;
END;
/
执行结果:
NOTICE: s(1) = 6.28
NOTICE: s(2) = 25.12
NOTICE: s(3) = 56.52
关联数组的内置函数
方法
描述
count()
返回元素的数量
delete(ain_index in binary_integer)
删除指定的元素
delete()
删除所有元素
exists(ain_index in binary_integer)
如果元素存在则返回true,否则返回false
first()
返回第一个元素的索引
last()
返回最后一个元素的索引
prior(ain_index in binary_integer)
返回指定元素之前的第一个元素的索引
next(binary_integer 中的ain_index)
返回指定元素之后的第一个元素的索引
示例:
\set SQLTERM /
DECLARE
TYPE num_table IS TABLE OF NUMBER INDEX BY PLS_INTEGER; -- 声明一个以PLS_INTEGER为索引的关联数组
t num_table; -- 声明关联数组变量
num INT;
BEGIN
t(1):='1';
t(10):='10';
raise notice '%',t(1);
raise notice '%',t(10);
raise notice 't.count=%',t.count();
num=t.first();
raise notice 'the first element is %',num;
num=t.next(num);
raise notice 'the next element is %',num;
num=t.last();
raise notice 'the last element is %',num;
num=t.prior(num);
raise notice 'the prior element is %',num;
if t.exists(1) then
raise notice 'element 1 exists';
end if;
raise notice 'delete element 10';
t.delete(10);
raise notice 'there are % elements',t.count();
raise notice 'delete all';
t.delete();
raise notice 'there are % elements',t.count();
END;
/
语法:
执行结果:
NOTICE: 1
NOTICE: 10
NOTICE: t.count=2
NOTICE: the first element is 1
NOTICE: the next element is 10
NOTICE: the last element is 10
NOTICE: the prior element is 1
NOTICE: element 1 exists
NOTICE: delete element 10
NOTICE: there are 1 elements
NOTICE: delete all
NOTICE: there are 0 elements