createorreplacefunction f_num_sal(vempno in emp.empno%type)return number
as
vsal number;beginselect sal into vsal from emp where empno=vempno;return vsal;end;/
createorreplaceprocedure f_deptno_avgdeptsal(vdeptno in emp.deptno%type)as
vsal number;beginselectavg(sal)into vsal from emp where deptno=vdeptno;
dbms_output.put_line('平均工資'||vsal);
dbms_output.put_line('比平均工資高的員工號、員工名');for v_emp in(select*from emp where deptno=vdeptno and sal>vsal)loop
dbms_output.put_line(v_emp.empno||'、'||v_emp.ename);endloop;end;
創建一個存儲過程,以部門號爲參數,返回該部門的人數和最高工資。
createorreplaceprocedure p_deptno_numandmaxsal(pdeptno emp.deptno%type)is
max_sal emp.sal%type;
a number;beginselectcount(*)into a from emp where deptno=pdeptno;
dbms_output.put_line('部門人數='||a);selectmax(sal)into max_sal from emp where deptno=pdeptno;
dbms_output.put_line('最高工資='||max_sal);end;
創建一個以部門號爲參數,返回該部門最高工資的函數。
createorreplacefunction f_deptno_maxsal(vdeptno in emp.deptno%type)return number
as
max_sal number;beginselect sal into max_sal from emp where empno=vdeptno;return max_sal;end;
使用存儲過程統計每個學生的‘已修學分’。
createtable stu(
sname char(10)notnull,
sno char(10)notnull,
tcredit number);createtable sc
(sno char(10)notnull,
cno char(10)notnull,
grade number,
credit number,primarykey(sno,cno));createtable course
(cno char(10)notnull,
cname char(20)notnull);insertinto sc values('100001','200001',69,5);insertinto sc values('100001','200002','50','4');insertinto course values('200002','數據庫系統設計');createorreplaceprocedure p_student_credit(
p_name out stu.sname%type,
p_credit out number)asbeginfor p in(select a.sname,sum(b.credit) credit
from stu a,sc b
where a.sno=b.sno)loop
dbms_output.put_line(p.sname||'、'||p.credit);endloop;end;
使用觸發器實現當登記學生成績(60分以上)時自動統計學生的‘已修學分’。
createorreplacetrigger t_insert_credit
afterinserton sc
for each rowbeginif :new.grade>=60thenupdate stu
set stu.tcredit=stu.tcredit+ :new.credit where stu.sno= :new.sno;endif;end;
createorreplacefunction f_cno_num(f_cno sc.cno%type)return number
as
num number;
name char(20);beginselect cname into name from course where cno=f_cno;selectcount(*)into num from sc where grade<60and cno=f_cno;
dbms_output.put_line(name||'未及格人數'||num);return num;end;
select f_cno_num(200002) 不及格人數 from dual;
將上實驗中的存儲過程與本實驗中函數創建包。
createorreplace package emp_package
isfunction f_num_sal(vempno in emp.empno%type)return number;procedure f_deptno_avgdeptsal(vdeptno in emp.deptno%type);procedure p_deptno_numandmaxsal(pdeptno emp.deptno%type);function f_deptno_maxsal(vdeptno in emp.deptno%type)return number;end emp_package;