14.定义并使用变量-参考变量
参照变量---介绍
参照变量是指用于存放数值指针的变量,通过使用参照变量,可以使得应用程序共享相同对象,从而降低占用的空间。在编写pl/sql程序时,可以使用游标变量(ref cursor)和对象类型变量(ref obj_type)两种参照变量类型
使用比较多的是游标变量
参照变量---ref cursor游标变量
使用游标时,当定义游标时不需要指定相应得select语句,但是当使用游标时(open时)需要指定select语句,这样一个游标就与一个select语句结合了,实例如下:
1.请使用pl/sql编写一个块,可以输入部门号,并显示该部门所有员工姓名和他的工资。
--输入部门号,并显示该部门所有员工姓名和他的工资。
declare
--定义游标类型 sun_emp_cursor
type sun_emp_cursor is ref cursor;
--定义一个游标变量
sun_cursor sun_emp_cursor;
--定义一个接收姓名的变量
v_ename emp.ename%type;
--定义一个接受工资的变量
v_sal emp.sal%type;
begin
--执行
--把sun_cursor和一个select结合
open sun_cursor for select ename,sal from emp where deptno=&no;
--循环取出
loop
fetch sun_cursor into v_ename,v_sal;
--判断退出循环的条件:判断sun_cursor是否为空
exit when sun_cursor%notfound;
dbms_output.put_line('员工名:'||v_ename||' 薪水:'||v_sal);
end loop;
--循环结束,关闭游标
close sun_cursor;
end;
2.在1的基础上,如果某个员工的工资低于2000元,就增加100元。
--输入部门号,并显示该部门所有员工姓名和他的工资。
declare
--定义游标类型 sun_emp_cursor
type sun_emp_cursor is ref cursor;
--定义一个游标变量
sun_cursor sun_emp_cursor;
--定义一个接收姓名的变量
v_ename emp.ename%type;
--定义一个接受工资的变量
v_sal emp.sal%type;
begin
--执行
--把sun_cursor和一个select结合
open sun_cursor for select ename,sal from emp where deptno=&no;
--循环取出
loop
fetch sun_cursor into v_ename,v_sal;
--判断退出循环的条件:判断sun_cursor是否为空
exit when sun_cursor%notfound;
if(v_sal<2000)
then v_sal:=v_sal+100;
end if;
dbms_output.put_line('员工名:'||v_ename||' 薪水:'||v_sal);
end loop;
--循环结束,关闭游标
close sun_cursor;
end;