oracle 创建过程与函数小记
---恢复内容开始---
--存储过程:
--案例1:
编写一个过程,输入员工姓名,和一个新工资,将emp表中的该员工的工资改为新工资
--1.结构:create or replace procedure 过程名(参数列表)is/as begin 执行语句 end;
--2.参数列表:name,newSal是一个形参。注意:不能给形参一个长度
--3.过程的使用:
create or replace procedure updateSal(name varchar2,newSal number) as begin update emp set sal=newSal where ename=name; end;
--案例2:
创建一个过程,输入一个员工编号,判断该员工的工资是否小于2000,如果小于2000,那么给他的工资加上500,通过参数,将新工资给传递出来
--1.in:表示是输入参数,out:表示输出参数,in out:表示输入输出参数
--2.在存储过程中,不能用declare关键字
--3.需要声明局部变量的时候结构:create or replace procedure 过程名(参数列表)is 局部变量的声明 begin 执行语句 end;
--4.如果没有写in,out,in out的话,默认的是输入参数。
create or replace procedure getNewSal(spNo in number,newSal out number) is v_sal emp.sal%type; begin select sal into v_sal from emp where empno=spNo; if v_sal<2000 then update emp set sal=sal+500 where empno=spNo; end if; select sal into newSal from emp where empno=spNo; end;
--案例3:
编写过程,输入一个部门编号,显示该部门员工的姓名,工资,入职日期
--1.存储过程中可以定义普通变量,还可以定义游标变量 create or replace procedure sp_pro5(spNo number) as --声明一个游标变量 cursor v_cursor is select ename,sal,hiredate from emp where deptno=spNo; v_ename emp.ename%type; v_sal emp.sal%type; v_date emp.hiredate%type; begin for v_cursors in v_cursor loop v_ename:=v_cursors.ename; v_sal:=v_cursors.sal; v_date:=v_cursors.hiredate; dbms_output.put_line('姓名:'||v_ename ||' 工资:'||v_sal||' 入职日期:'||v_date); end loop; end; --执行过程 declare v_deptno emp.deptno%type:=&no; begin sp_pro5(v_deptno); end;
--删除存储过程
--drop procedure 过程名
eg:
drop procedure sp_pro1;
--函数:
--案例4:
创建一个函数,输入一个员工编号,判断该员工的工资是否小于2000,如果小于2000,那么给他的工资加上500,返回新工资。
--总结:1.结构:create [or replace] function 函数名(参数列表) return 返回值的类型 is|as 局部变量 begin 执行语句 end;
--2.在执行语句中,需要有一个return语句,来返回一个值。
--3.在用函数的时候,返回一个值。如果确实需要获得多个值,一般使用存储过程,通过参数列表中的out参数获得(输出参数)
create or replace function getEmpNewSal(spNo in number) return number is --定义一个局部变量 v_sal emp.sal%type; v_newSal emp.sal%type; begin select sal into v_sal from emp where empno=spNo; if v_sal<2000 then update emp set sal = sal+500 where empno=spNo; end if; select sal into v_newSal from emp where empno=spNo; return v_newSal; end;
--调用函数
declare
v_empno emp.empno%type:=&no;
v_newSal emp.sal%type;
begin
v_newSal:=getEmpNewSal(v_empno);
dbms_output.put_line(v_newSal);
end;
--案例5:
创建一个函数,输入一个员工编号,判断该员工的工资是否小于2000,如果小于2000,工资加上500,否则加200,返回新工资。
--return:函数中可以有多个return语句,但是只返回一次的。执行return语句,函数将执行结束并返回结果
create or replace function getEmpNewSal(spNo in number) return number is --定义一个局部变量 v_sal emp.sal%type; v_newSal emp.sal%type; begin select sal into v_sal from emp where empno=spNo; if v_sal<2000 then update emp set sal = sal+500 where empno=spNo; select sal into v_newSal from emp where empno=spNo; return v_newsal; else update emp set sal = sal+200 where empno=spNo; select sal into v_newSal from emp where empno=spNo; return v_newSal; end if; end;
--删除函数:
drop function 函数名
eg:
drop function sp_func1;
---恢复内容结束---