Oracle学习之复合数据类型
1 .使用 %type 定义变量
为了让PL/SQL中变量的类型和数据表中的字段的数据类型一致,Oracle 9i提供了%type定义方法。
这样当数据表的字段类型修改后,PL/SQL程序中相应变量的类型也自动修改.
/**//*
Declare
mydate student.sdate%type;
begin
commit;
end;
*/
2. 定义记录类型变量
将多个基本数据类型捆绑在一起的记录数据类型。
/**//*
set serveroutput on
declare type myrecord is record(
sid int,
sname varchar2(50));
srecord myrecord; --声明一个自定义记录类型变量的实例
begin
select id,name into srecord from liutest where id=1;
dbms_output.put_line('ID: '|| srecord.sid ||'Name:'|| srecord.sname); --'||': 它是字符串连接符.
end;
*/
3.使用 %rowtype 变量
使用%type可以使变量获得字段的数据类型,使用%rowtype可以使变量获得整个记录的数据类型。
比较两者定义的不同:变量名 数据表.列名%type,变量名 数据表%rowtype。
/**//*
set serveroutput on
Declare
mytableRow liutest%rowtype;
begin
select * into mytableRow
from liutest
where id=1;
dbms_output.put_line(mytableRow.id || mytableRow.name);
end;
*/
4.定义一维表类型变量
表类型变量和数据表是有区别的,定义表类型变量的语法如下:
―――――――――――――――――――――――――――――――――――――
type 表类型 is table of 类型 index by binary_integer;
表变量名 表类型;
―――――――――――――――――――――――――――――――――――――
类型可以是前面的类型定义,index by binary_integer子句代表以符号整数为索引,
这样访问表类型变量中的数据方法就是“表变量名(索引符号整数)”。
/**//*
Declare
type tabletype1 is table of varchar2(6) index by binary_integer; --定义一个字符型的一维数组
type tabletype2 is table of liutest.id%type index by binary_integer;--定义了一个整数数型的数组
table1 tabletype1; --实例声明
table2 tabletype2; --实例声明
begin
table1(1):='测试一';
table1(2):='测试二';
table2(1):=88;
table2(2):=89;
dbms_output.put_line(table1(1)||table2(1));
dbms_output.put_line(table1(2)||table2(2));
end;
*/
5.定义多维类型表变量
相当于定义多维数组.
注意在运行下面的语句前要在数据库中插入数据.
Declare
type tabletype1 is table of liutest%rowtype index by binary_integer;
table1 tabletype1;
begin
select * into table1(50)
from liutest
where id=50;
dbms_output.put_line(table1(50).id ||table1(50).name);
end;