您的位置:首页 > 其它

存储过程三个例子

2015-11-10 14:06 211 查看
/*

实例1:统计每年入职的员工个数。

可能SQL:

select to_char(hiredate,’yyyy’) from emp;

*/

set serveroutput on

declare

cursor cemp is select to_char(hiredate,’yyyy’) from emp;

phiredate varchar2(4);

–计数器

count80 number := 0;

count81 number := 0;

count82 number := 0;

count87 number := 0;

begin

open cemp;

loop

–取一个员工

fetch cemp into phiredate;

exit when cemp%notfound;

--判断
if phiredate = '1980' then count80:=count80+1;
elsif phiredate = '1981' then count81:=count81+1;
elsif phiredate = '1982' then count82:=count82+1;
else count87 := count87+1;
end if;


end loop;

close cemp;

–输出

dbms_output.put_line(‘total:’||(count80+count81+count82+count87));

dbms_output.put_line(‘1980:’|| count80);

dbms_output.put_line(‘1981:’|| count81);

dbms_output.put_line(‘1982:’|| count82);

dbms_output.put_line(‘1987:’|| count87);

end;

/

/*

为员工长工资。从最低工资调起每人长10%,但工资总额不能超过5万元,

请计算长工资的人数和长工资后的工资总额,并输出输出长工资人数及工资总额。

可能的SQL:

员工: select empno,sal from emp order by sal;

长工资后的工资总额:1. 对sal进行累加: 新的工资总额=旧的工资 + sal*0.1;

2. sum(sal): 查询数据库

练习: 工资不能超过5w

*/

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

–工资总额>5w

exit when salTotal > 50000;

–取一个员工

fetch cemp into pempno,psal;

exit when cemp%notfound;

--涨工资
update emp set sal=sal*1.1 where empno=pempno;
--人数
countEmp := countEmp +1;
--工资总额
salTotal := salTotal + psal * 0.1;


end loop;

close cemp;

commit;

–输出

dbms_output.put_line(‘长工资的人数:’|| countEmp);

dbms_output.put_line(‘工资总额:’|| salTotal);

end;

/

/*

用PL/SQL语言编写一程序,实现按部门分段(6000以上、(6000,3000)、3000元以下)

统计各工资段的职工人数、以及各部门的工资总额(工资总额中不包括奖金)

SQL语句:

部门: select deptno from dept;

员工的工资: select sal from emp where deptno=???

工资总额: select sum(sal) from emp where deptno=???

*/

set serveroutput on

declare

–部门

cursor cdept is select deptno from dept;

pdno 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 pdno;

exit when cdept%notfound;

--初始化
count1 :=0;count2:=0;count3:=0;
select sum(sal) into salTotal  from emp where deptno=pdno;

--取部门中的员工
open cemp(pdno);
loop
fetch cemp into psal;
exit when cemp%notfound;

--判断
if psal<3000 then count1:=count1+1;
elsif psal>=3000 and psal<6000 then count2:=count2+1;
else count3:=count3+1;
end if;
end loop;
close cemp;

--保存当前部门
insert into msg1 values(pdno,count1,count2,count3,nvl(salTotal,0));


end loop;

close cdept;

commit;

dbms_output.put_line(‘完成’);

end;

/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: