问题:
1、建立存储过程,将指定部门编号的员工工资增加m%(m>0),并将此部门名称和增加的总金额传递到外部环境。当指定部门号不存在时,进行异常处理;当m<0时,进行异常处理。
2、在同一程序块内调用以上存储过程,分别将10、20、30号部门的员工工资增加10%、20%和30%,同时输出每个部门的编号、部门名称和增加的总金额。
我自己写的解决代码,程序比较简单,
create or replace procedure sun_sal(
emp_sum out emp.sal%type, --增加工资差额
dept_dname out dept.dname%type, --输出部门名称
emp_count out number, --实现伪no_data_found
emp_deptno in emp.deptno%type, --输入部门号
emp_plusnumber in number --增加工资百分比
) is
begin
if emp_plusnumber<0 then
raise NO_DATA_FOUND;
end if;
--因为开发环境不报no_data_found错误,所以自己写一个
select count(*) into emp_count from emp where deptno=emp_deptno;
if emp_count=0 then
raise NO_DATA_FOUND;
end if;
--从dept查部门名存入dept_dept_dname
select dname into dept_dname from dept where deptno=emp_deptno;
--从emp查增加的工资总额存入emp_sum
select sum(sal)*emp_plusnumber/100 into emp_sum from emp where deptno=emp_deptno;
--对表更新
update emp set sal=sal((100+emp_plusnumber)0.01) where deptno=emp_deptno;
commit;
dbms_output.put_line('部门名称为:'|| dept_dname);
dbms_output.put_line('指定部门号工资增加了:'||emp_sum);
exception
when NO_DATA_FOUND then
dbms_output.put_line('该部门号不存在-或不能减少工资!!');
end sun_sal;
标准答案
create or replace procedure updata_dept(
num_deptno in dept.deptno%type,
m in number,
var_dname out dept.dname%type,
tot_sal out emp.sal%type) is
begin
if m>0 then
select dname into var_dname from dept where deptno = num_deptno;
select sum(sal)*(m/100) into tot_sal from emp where deptno = num_deptno;
update emp set sal = sal*(1+m/100) where deptno = num_deptno;
else
dbms_output.put_line('m<0,不合理');
end if;
exception
when no_data_found then
dbms_output.put_line('该部门号不存在');
end;
/
另外马老师写的代码中还用到了游标,但我认为这样会使程序复杂,使可读性下降
这是个很简单的小程序,中间耗费我大量时间的主要是我的开发环境不报NO_DATA_FOUND这个错误使程序无法继续,所以自己做了异常
那为什么要记录这个这么简单的小程序呢,有两个小原因
1.上学期李娜老师讲spring关于数据库部分时,提过如果使用存储过程管理数据插入(主键自增),将提高程序执行效率,那时看着那堆程序压根不懂,现在却能自己写出来,记录自己的成长
2.齐斐齐老师是以为非常棒的老师,在我朴素的认识中,只有像齐斐李娜这样的老师才对得起我交的学费,齐老师上课说过,这是他自己出的小程序,网上应该找不到答案,到目前为止之用过两次,这次和上一届用过一次这个程序,除非上一届有那个同学做出来了程序,然后骄傲的发到网上,
我没有搜索过,但现在,我就是那个写出程序的骄傲的同学,请允许我向这个世界道出我的自豪,哪怕只有一点点,那怕声音很小,