在编写pl/sql程序时,可以定义变量和常量
a.标量类型(scalar)
b.复合类型(composite)
c.参照类型(reference)
d.lob(large object)
标量类型(scalar)
declare
c_tax_rate number(3,2):=0.03;
--用户名
--v_ename emp.ename%type;(这种定义灵活)
v_ename varchar2(5);
v_sal number(7,2);
v_tax_sal number(7,2);
begin
--执行
select ename,sal into v_ename,v_sal from emp where empno=&no;
--计算所得税
v_tax_sal:=v_sal*c_tax_rate;
--输出
dbms_output.put_line('姓名是:'||v_ename||'工资:'||v_sal||'交税:'||v_tax_sal);
end;
复合类型(composite)
用于存放多个值的变量。主要报错这几种:
a.pl/sql记录
类似于高级语言中的结构体(可以理解为java中的类),需要注意的是,
当引用pl/sql记录成员时,必须要加记录变量作为前缀(记录变量.记录成员)
b.pl/sql表
相当于高级语言中的数组,但是需要注意的是在高级语言中数组的下标不能为负数,
而pl/sql是可以为负数的,并且表元素的下标没有限制
c.嵌套表
d.varray
--pl/sql记录 案例
***下面两条下划线顺序要一致不然报错
declare
--定义一个pl/sql记录类型 emp_record_type,类型包含三个数据,分别是name salary title
type emp_record_type is record(name emp.ename%type,salary emp.sal%type,title emp.job%type);
--定义一个sp_record变量,这个变量的类型是emp_record_type
sp_record emp_record_type;
begin
selectename,sal,job into sp_record
from emp where empno=7788;
dbms_output.put_line('员工名:'||sp_record.name||'工资是'||sp_record.salary);
end;
--pl/sql表 案例
declare
--定义一个pl/sql表类型 sp_table_type ,该类型是用于存放emp.ename%type这种类型的数组
--index by binary_integer 表示下标是整数(负数+正数)
type sp_table_type is table of emp.ename%type index by binary_integer;
--定义一个 sp_table 变量, 这个变量的类型是 sp_table_type
sp_table sp_table_type;
begin
select ename into sp_table(0) from emp where empno=7788;
dbms_output.put_line('员工名:'||sp_table(0));
end;
说明:
sp_table_type 是pl/sql表类型
emp.ename%type 指定了表的元素的类型和长度
sp_table 为pl/sql表变量
sp_table(0)则表示下标为0的元素
参照类型(reference)
参照变量是指用于存放数值指针的变量。通过使用参照变量,可以使用应用程序共享相同对象,
从而降低占用的空间。在编写pl/sql程序时,可以使用游标变量(ref cursor)和对象类型变量
(ref obj_type)两种参照变量类型
游标变量(ref cursor)
使用游标时,当定义游标时不需要指定相应的select语句,但是当使用游标时(open时)需要
指定select语句,这样一个游标就与一个select语句结合
案例:
--使用pl/sql编写一个块,可以输入部门号,并显示该部门
declare --定义游标类型 type sp_emp_cursor is ref cursor; --定义一个游标变量 test_cursor sp_emp_cursor; v_ename emp.ename%type; v_sal emp.sal%type; begin --执行 --把test_cursor 和一个select结合 open test_cursor for select ename,sal from emp where deptno=&no; --循环取出 loop fetch test_cursor into v_ename,v_sal; --判断工资高低,决定是否... --判断是否test_cursor为空 exit when test_cursor%notfound; dbms_output.put_line('名字:'||v_ename||'工资:'||v_sal); end loop; end;