pl/sql编程(三)函数

函数

函数用于返回特定的数据(一般返回一个值)。当建立函数时,函数头部必须包含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()函数表示如果commnull,则赋值为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;




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值