函数
函数用于返回特定的数据(一般返回一个值)。当建立函数时,函数头部必须包含return子句,而在函数体内必须包含return语句返回的数据。
可以使用create function命令来建立函数。
实例1
--函数案例 --输入雇员的姓名,返回该雇员的年薪 create function GetYearSal(name varchar) return --返回值的定义部分 number is yearSal number(7,2); begin --执行部分 select sal*12+nvl(comm,0)*12 into yearSal from emp where ename=name; --nvl()函数表示如果comm为null,则赋值为0 return yearSal; end;
在sqlplus中调用函数的步骤: sql>var income number sql>call GetYearSal('SCOTT') into:income sql>print income |
上例子:
创建的窗口
测试的窗口:
例子一:
-----------------------自定义函数----------------
create or replace function myFn(e_name in varchar,e_deptno in number)
return boolean is
--is后面声明局部变量
flag boolean:=false;
i integer:=0;
begin
select count(*) into i from emp where emp.ename=e_name and emp.deptno=e_deptno;
if i>0 then
flag:=true;
else flag:=false;
end if;
return flag;
end myFn;
-------------测试:
-- Created on 2015/8/26 by ADMINISTRATOR
declare
i boolean;
begin
-- Test statements here
i:=myfn('SMITH',20);
/*注意:函数可以在sql中调用,如果返回值boolean
此时dbms输出不了,因此无法调用返回boolean的函数
在plsql中调用函数,必须用变量接受返回值,否则认为调用的是存储过程
*/
if i then
dbms_output.put_line('true');
else
dbms_output.put_line('false');
end if;
end;
例子二:
自定义函数:
create or replace function nvlComm(targetcomm in emp.comm%type) return varchar2 is
begin
if targetcomm is null
then
return 'no-comm';
else
return targetcomm;
end if;
end nvlComm;
-------测试:
select nvlcomm(comm) from emp
例子三:
create or replace function Test(e_empno in number,e_row out emp%rowType)
return boolean is
flag boolean :=false;
i number;
begin
select empno into i from emp where emp.empno=e_empno;
if sql%found then--如果有行记录
select * into e_row from emp where emp.empno=e_empno;
flag:=true;
else
flag:=false;
end if;
return flag;
exception when no_data_found
then return false;
When others then return false;
end Test;
-----------------测试:
declare
i boolean;
emp_row emp%rowtype;
begin
i:=test('769',emp_row);
if i then
dbms_output.put_line(emp_row.empno||emp_row.ename);
end if;
end;