declare
--定义加薪比例常量
c_manager constant number :=0.15;
c_salesman constant number :=0.12;
c_clerk constant number :=0.10;
v_job varchar(100); --定义职员变量
v_empno varchar(20); --定义员工编号变量
v_ename varchar(60); --定义员工名称变量
cursor c_emp
is
select job,empno,ename
from scott.emp
for update;
begin
open c_emp; --打开游标
loop --循环游标
fetch c_emp
into v_job,v_empno,v_ename; --提取游标数据
exit when c_emp%notfound; --如果无数据可提取则退出游标
if v_job='clerk'
then --如果为职员,加薪10%
update scott.emp
set sal=sal*(1+c_clerk)
where current of c_emp;
elsif v_job='salesman'
then --如果为销售职员,加薪12%
update scott.emp
set sal=sal*(1+c_salesman)
where current of c_emp;
elsif v_job='manager'
then --如果为经理,加薪15%
update scott.emp
set sal=sal*(1+c_manager)
where current of c_emp;
end if ;
--显示完成信息
dbms_output.put_line ('已经为员工'
||v_empno
||':'
||v_ename
||'成功加薪!'
);
end loop;
close c_emp; --关闭游标
exception
when no_data_found
then --处理PL/SQL预定义异常
dbms_output.out_line('没有找到员工数据');
end;
代码的执行流程如以下步骤所示:
(1)定义一个名为c_emp的游标,PL/SQL中的游标通常用来处理select语句返回的多行数据。
(2)为了提取游标指向的多行数据,在代码中使用了loop-end loop语法。循环调用fetch语句提取数据,exit when语句在无数据提取后,将退出循环。
(3)在提取到了数据后,通过分支结构根据员工的职级为员工进行了加薪,执行这个语句块后,可以看到再dbms_output输出区中显示了多行加薪成功的信息,表示循环已经成功执行。