/*
为员工涨工资,从最低工资涨起,每人涨10%,但工资总额不能超过5万元,请计算涨工资的人数和涨工资后的工资总额,并输出涨工资人数及工资总额。
SQL语句
select empno,sal from emp order by sal;
à光标à循环à退出条件:1、工资总额>5万 2、%notfound
变量:1、初始值2、如何得到
涨工资的人数:
countEmp number:=0;
涨后的工资总额:
salTotal number;
- select sum(sal) into salTotal from emp;
- 涨后的工资总额=涨前的工资总额+sal*0.1(操作数据库比运算慢,所以这个方法比较好)
*/
set serveroutput on
declare
--定义光标
cursor cemp is select empno,sal from emp order by sal;
pempno emp.empno%type;
psal emp.sal%type;
--涨工资的人数
countEmp number:=0;
--涨后的工资总额
salTotal number;
begin
--得到工资总额的初始值
select sum(sal) into salTotal from emp;
--打开光标
open cemp;
loop
--1、工资总额>5万
exit when salTotal>50000;
--取一个员工涨工资
fetch cemp into pempno,psal;
-- 2、%notfound
exit when cemp%notfound;
--涨工资
if salTotal+psal*1.1<50000 then
update emp set sal=sal*1.1 where empno=pempno;
--人数+1
countEmp:=countEmp+1;
--2、涨后的工资总额=涨前的工资总额+sal*0.1
salTotal:=salTotal+psal*0.1;
end loop;
--关闭光标
close cemp;
commit;
--打印结果
dbms_output.put_line(‘人数:’||countEmp||‘涨后的工资人数:’||salTotal);
end;
/