变量
变量名 变量名类型(类型范围);
e.g: v_name varchar2(8);
V_process_time date;--处理时间
赋值语句:
变量名:=值;
1.1 boolean 类型定义:
v_bflag boolean not null default false;
1.2 常量定义:
v_tax_rate constant number(3,2):=0.03
1.3 定义数组:
type arrays is table of varchar2(200);
1.4 使用 %type类型:
使用这个属性时候,它会按照数据库列或其它变量来确定新变量的类型和长度
v_name emp.name%type
1.4.1 单行多列 使用pl/sql 记录
a.自定义
type emp_record_type is RECORD(
name emp.name%TYPE,--定义成emp表中name的数据类型
sal emp.sal ,
);
emp_record emp_record_type;
使用:
emp_record.name
b.定义行记录
dept_record dept%ROWTYPE
1.4.2 多行多列
为了处理多行单列,多行多列使用pl/sql集合如: 索引表,嵌套表,varray。
a) pl/sql表(索引表)。
只能用在pl/sql中同种类型的一维、无边界的同类元素稀疏集合,且只能是由一列组成。
定义:type ename_table_type is table of varchar2(200) index by binary_integer;
或者type ename_table_type is table of emp.ename%type index by binary_integer;
声明:ename_table ename_table_type;
select ename into arrays(-1) from emp where empno=7788 把员工姓名放入 下标为-1的空间。
b) 嵌套表也是一维、无边界稀疏集合
定义:type ename_table_type is table of varchar2(200);
或者type arrays is table of emp%name;
嵌套表的下标从1开始,也是属于稀疏集合,和索引表的区别除了开始下标以外,而且嵌套表是可以做为表列的数据类型,而索引表不可以。
并且必须使用初始化构造函数初始化
emp_array ename_table_type=:ename_table_type();//构造方法初始化
eg:
type emp_table_type is table of emp.name%type;
emp_table emp_table_type:=emp_table_type();
select ename into emp_table(2) from emp where empno='1779';
dbms_output.putLine(emp_table(2));
结果:scott
1.4.3 定义数组类型
type arrays is table of varchar2(200);
--初始化
dataList arrays := arrays();
--作为参数传递
procedure pro_name(dataList is arrays) is
begin
end ;
/*
用指定字符将字符串分隔为数组
str 字符串
str_split 分割字符
return 分割后的数组
*/
function splitString(sourceString varchar2, splitFlag varchar2)
return arrays is
dataList arrays := arrays(); --一定要,构造函数初始化
temp varchar2(200); --存储临时数据
tempSource varchar2(1000) := sourceString; --存储需要分割的字符串()
splitIndex number(2); --分隔符在字符串中首次出现的位置
splitLength number(2) := length(splitFlag); --分割符长度
begin
while instr(tempSource, splitFlag) > 0 loop
splitIndex := instr(tempSource, splitFlag);
--取出第一个分割符前的字符串
temp := substr(tempSource, 1, splitIndex - splitLength);
--减去第一个分隔符前的字符串
tempSource := substr(tempSource,
splitIndex + splitLength,
length(tempSource));
if temp is not null then
dataList.extend(1);
dataList(dataList.count) := temp;
end if;
end loop;
if tempSource is not null then
dataList.extend(1);
dataList(dataList.count) := tempSource;
end if;
return dataList;
end splitString;
c) varray 变长数组 做为表列的数据类型,并且必须指定数组的大小
TYPE t_name IS VARRAY(2) OF VARCHAR2 (10); 定义了一个字符类型的数组,并且只能存储两个元素
存储对象类型:
create type article_type as OBJETC(
title varchar2(20),
pubDate DATE
)
create type article_array is varray(2) of article_type
可以当作用户自定义数据类型来引用:
create table author(
id number,
name varchar2,
arti article
)
1.4.4 集合内置的方法
COUNT返回集合中元素的个数;
DELETE删除集合中所有元素;
DELETE(x)删除元素下标为x的元素对VARRAY非法;
DELETE(x,y)删除元素下标从X到Y的元素对VARRAY非法;
EXIST(x)如果集合元素x已经初始化,则返回TRUE,否则返回FALSE;
EXTEND在集合末尾添加一个元素对Index_by非法;
EXTEND(x)在集合末尾添加x个元素对Index_by非法;
EXTEND(x,n)在集合末尾添加元素n的x个副本对Index_by非法;
FIRST返回集合中的第一个元素的下标号,对于VARRAY集合始终返回1。;
LAST返回集合中最后一个元素的下标号,对于VARRAY返回值始终等于COUNT。