PL/SQL实例
1. 统计每年入职的员工人数
1 set SERVEROUTPUT ON; 2 declare 3 cursor cemp is select to_char(hiredate,'yyyy') from emp; 4 phiredate VARCHAR2(4); 5 count80 number:=0; 6 count81 number:=0; 7 count82 number:=0; 8 count83 number:=0; 9 begin 10 open cemp; 11 loop 12 fetch cemp into phiredate; 13 exit when cemp%notfound; 14 if phiredate='1980' then count80:=count80+1; 15 elsif phiredate='1981' then count81:=count81+1; 16 elsif phiredate='1982' then count82:=count82+1; 17 else count83:=count83+1; 18 end if; 19 end loop; 20 close cemp; 21 dbms_output.put_line('total:'||(count80+count81+count82+count83)); 22 end; 23 /
2. 员工涨工资问题,问题点;多次执行涨工资后,总工资会超过6000,需在更新前判断总工资是否有超过6000,有则不更新
1 declare 2 cursor cemp is select empno,sal from emp order by sal; 3 countEmp number:=0; 4 salTotal number; 5 pempno emp.empno%TYPE; 6 psal emp.sal%TYPE; 7 8 begin 9 select sum(sal) into salTotal from emp; 10 open cemp; 11 loop 12 exit when saltotal>6000; 13 fetch cemp into pempno,psal ; 14 exit when cemp%notfound; 15 update emp set sal=sal+sal*0.1 where empno=pempno; 16 countEmp:=countEmp+1; 17 salTotal:=salTotal+psal*0.1; 18 end loop; 19 close cemp; 20 commit; 21 dbms_output.put_line('涨工资人数:'||countEmp||','||'涨薪总额'||salTotal); 22 end;
3. 多张表涨工资问题:实现按部门分段(6000以上,6000-3000,3000以下)统计各工资段的职工人数,以及各部门的工资总额。
set SERVEROUTPUT ON; declare cursor cdept is select deptno from dept; pdeptno dept.deptno%type; cursor cemp(dno number) is select sal from emp where deptno=dno; psal emp.sal%TYPE; count1 number; count2 number; count3 number; saltotal number; begin open cdept; loop fetch cdept into pdeptno ; exit when cdept%notfound; count1:=0; count2:=0; count3:=0; saltotal:=0; select sum(sal) into saltotal from emp where deptno=pdeptno; open cemp(pdeptno); loop fetch cemp into psal; exit when cemp%notfound; if psal <3000 then count1:=count1+1; elsif psal>6000 then count3:=count3+1; else count2:=count2+1; end if; end loop; close cemp; insert into msg values(pdeptno,count1,count2,count3,saltotal); end loop; close cdept; dbms_output.put_line('统计完成'); end;
4. 带输入参数和输出参数的执行
create or replace PROCEDURE p_hello(p_empno in emp.empno%type, p_sal out emp.sal%type) as begin select sal into p_sal from emp where empno=p_empno; end;
执行时,需要定义一个参数,用来存储输出参数的值:
declare p_sal emp.sal%type; begin p_hello(8003,p_sal); end;

浙公网安备 33010602011771号