實驗三 存儲過程和函數

  1. 創建一個函數,以員工號爲參數,返回該員工的工資。
create or replace function f_num_sal(vempno in emp.empno%type) return number
as
vsal number;
begin
select sal into vsal from emp where empno=vempno;
return vsal;
end;
/
  1. 創建一個存儲過程,以部門號爲參數,查詢該部門的平均工資,並輸出該部門中比平均工資高的員工號、員工名。
create or replace procedure f_deptno_avgdeptsal(vdeptno in emp.deptno%type)
as
vsal number;
begin
select avg(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);
end loop;
end;
  1. 創建一個存儲過程,以部門號爲參數,返回該部門的人數和最高工資。
create or replace procedure p_deptno_numandmaxsal(pdeptno emp.deptno%type)
is
max_sal emp.sal%type;
a number;
begin
select  count(*) into a from emp where deptno=pdeptno;
dbms_output.put_line('部門人數='||a);
select max(sal) into max_sal from emp where deptno=pdeptno;
dbms_output.put_line('最高工資='||max_sal);
end;
  1. 創建一個以部門號爲參數,返回該部門最高工資的函數。
create or replace function f_deptno_maxsal(vdeptno in emp.deptno%type) return number
as
max_sal number;
begin
select sal into max_sal from emp where empno=vdeptno;
return max_sal;
end;
  1. 使用存儲過程統計每個學生的‘已修學分’。
create table stu(
sname char(10) not null,
sno char(10) not null,
tcredit number);

create table sc
(sno char(10) not null,
cno char(10) not null,
grade number,
credit number,
primary key (sno,cno));

create table course
(cno char(10) not null,
cname char(20) not null);
insert into sc values('100001','200001',69,5);
insert into sc values('100001','200002','50','4');
insert into course values('200002','數據庫系統設計');

create or replace procedure p_student_credit(
p_name out stu.sname%type,
p_credit out number)
as
begin
for 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);
end loop;
end;
  1. 使用觸發器實現當登記學生成績(60分以上)時自動統計學生的‘已修學分’。
create or replace trigger t_insert_credit
after insert on sc
for each row
begin
if :new.grade>=60 then
update stu 
set stu.tcredit=stu.tcredit+ :new.credit where stu.sno= :new.sno;
end if;
end;
  1. 使用函數實現統計各課程的未及格人數,要求輸入參數課程號後,返回各課程的人數NUM。並實現調用,查‘數據庫系統設計’的未及格人數。
create or replace function f_cno_num(f_cno sc.cno%type) return number
as
num number;
name char(20);
begin
select cname into name from course where  cno=f_cno;
select count(*) into num from sc where grade<60 and cno=f_cno;
 dbms_output.put_line(name||'未及格人數'||num);
return num;
end;
select f_cno_num(200002) 不及格人數 from dual;
  1. 將上實驗中的存儲過程與本實驗中函數創建包。
create or replace package emp_package
is
function 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;
發佈了9 篇原創文章 · 獲贊 14 · 訪問量 3333
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章