过程,函数,触发器的创建与使用

过程的创建

//格式
create or replace procedure procedure_name(p_name type)
as
v_name type;
begin
  *****
end;
//实例  按照输入的员工号查找部门然后增加工资
create or replace procedure add_sal(p_empno emp.empno%type)
as
   v_addsal number(4);
   v_deptno  emp.deptno%type;
begin
   select deptno into v_deptno from emp where empno=p_empno;
   if     v_deptno=10 then v_addsal:=150;
   elsif v_deptno=20 then v_addsal:=200;
   elsif v_deptno=30 then v_addsal:=250;
   else  v_addsal:=300;
   end if;
   update emp set sal = sal + v_addsal where
          empno = p_empno;
   dbms_output.put_line('以增加'||v_addsal||'');
 end;
//过程的调用
execute add_sal(7788);
//或者
declare
begin
  add_sal(7788);
end;

函数的创建

//以员工号为参数,返回该员工所在部门的平均工资。
create or replace function avg_sal(f_empno in emp.empno%type)
return emp.sal%type
as 
  avg_sal emp.sal%type;
begin
  select avg(sal) into avg_sal from emp where 
  deptno=(select deptno from emp where empno=f_empno);
  return avg_sal;
end;
//调用
begin
    dbms_output.put_line(avg_sal(7788));
end;

触发器

//在emp表上创建一个触发器,当插入、删除或修改员工信息时,
//统计出操作后的员工人数和平均工资,并输出。
create or replace trigger count_avg_sal 
after insert or delete or update 
on emp
declare
  v_avg_sal emp.sal%type;
  v_count   number;
begin
  select avg(sal),count(*) into v_avg_sal,v_count from emp;
  dbms_output.put_line('平均工资是:'||v_avg_sal||'总人数是:'||v_count);
end;

//满足触发条件就会触发
update emp set sal=3000 where empno=7788;
原文地址:https://www.cnblogs.com/mobai95/p/12516644.html