您的位置:首页 > 数据库 > Oracle

oracle 三种复合类型变量分析

2016-05-13 01:16 573 查看
实际项目中,经常遇到的三种复合类型变量。结合部分项目实例做个整理,具体如下:
记录类型:记录类型可以包含一个或多个成员,而每个成员的类型可以不同,成员可以是标量类型。也可以引用其他的变量类型。这种类型的特点是比较适合处理查询语句中有多个列的情况,最常用的情况就如在调用某一张表中的一行记录。

索引表类型(关联数组):索引表类型和数组相似,他利用键值查找对应的值,这里的键值同真正数组的下标不同,索引表中下标允许使用字符串。数组的长度不是固定值,可以根据需要自动增长。其中的键值是整数或是字符串,其中的值就是普通的标量类型,也可以是记录类型。(下标从1开始)

VARRAY 变长数组:变长数组的元素个数需要限制,他是一个存储有序元素的集合,数组的下标从1开始,适合较少数据时使用。

eg1:记录类型-
declare
type pro_x is record
(v_id product_info.id%type,
v_name varchar2(10),
v_price number(8,2));

v_pro pro_x;//声明变量 v_pro,v_pro的数据类型是pro_x类型。

begin
select id,name,price into v_pro from product_info where id='11011211410086';
dbms_output.put_line('id:'||v_pro.v_id||','||'name:'||v_pro.v_name||','||'price:'||v_pro.v_price);
end;

记录类型声明方式:type type_name is record(field_name datatype[not null]{:=|default}expression) 说明:not null 可以约束记录成员非空。
可以使用%rowtype进行代替,实现上述功能。即:
declare
v_pro product_info%rowtype;
begin
select id,name,price into v_pro from product_info where id='11011211410086';
dbms_output.put_line('id:'||v_pro.id||','||'name:'||v_pro.name||','||'price:'||v_pro.price);
end;
eg2:索引表类型(关联数组)---身份证校验
declare
type TiArray is table of integer;
type TcArray is table of varchar2(1);
type id_emp is table of qlr_info%type
index by binary_integer;
rst id_emp;
W TiArray;
A TcArray;
S integer;
tab varchar2(200);
zuihyw varchar2(1);
jieguo number;
shenfzh varchar2(20);
cursor c is
select zjbh from qlr_info where length(zjbh)=18 and zjzl='居民身份证' and regexp_like(substr(zjbh,1,17),'^[0-9]*$');//regexp_like(substr(zjbh,1,17),'^[0-9]*$') 表示查找截取的前17为字符串为数字。^:匹配开始位置;$:匹配结束位置;*:匹配零次或多次。
begin
W:=TiArray(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2);
A:=TcArray('1','0','X','9','8','7','6','5','4','3','2');
for emc in c
loop
S:=0;
shenfzh:=emp.zjbh;
for i in 1..17 loop
S:=S+to_number(substr(shenfzh,i,1)*W(i));
end loop;
jieguo:=S mod 11;
zuihyw:=A(jieguo+1);
zuihyw2:=substr(shenfzh,18,1);
if (zuihyw<>zuihyw2) then
dbms_output_line('证件编号:'emp.zjbh||'错误!')
end if;
end loop;
end;
eg2.1使用字符串为键值的索引表
declare
type pro is table of number(8) index by varchar2(20);
v_pro pro;
begin
v_pro('test'):=253;
v_pro('test1'):=256;
dbms_out.put_line(v_pro.first ||','||v_pro(v_pro.first));
end;
索引表类型声明:
type type_name is table of {column_type|variable_name%type|table_name%rowtype}[not null] index by {pls_integer|binary_integer|varchar2(v_size)}

eg3,变长数组
declare
type varr is  varray(10) of varchar2(10);//定义数组长度10
v_pro varr:=varr('1','2');//初始化了两个元素(最多可以初始化10个)
begin
v_pro(1):='haha';
v_pro(2):='ouou';
dbms_output.put_line(v_pro(1)||','||v_pro(2));
end;
变长数组声明:type type_name is {varray|varying array}(size_limit)of element_type[not null]

2016.05.11


本文出自 “MST” 博客,转载请与作者联系!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: