Oracle學習筆記之用戶自定義函數


 

自定義函數語法格式:

 

 

  用戶自定義的函數,可以直接在sql語句中直接調用,並且任何一個funciton都必須有返回值,而且該函數聲明后,是保存在數據端的,我們隨時可以使用;注意:函數只能有一個返回值,如果想返回多個數據,可通過out類型參數將數據傳到函數外部;

例如:定義一個函數,該函數根據員工姓名以及部門編號,查找該員工是否在emp中存在,如果存在返回true否則返回false;

createorreplacefunction myFunction(mName invarchar2,mNo innumber)returnbooleanis

  flag boolean:=false;

  total number;

 

begin

    selectcount(*)into total  from emp where emp.ename=mName and emp.deptno=mNo;

    if total>0then

      flag:=true;

    else flag:=false;

    endif;

  return flag;

end myFunction;

測試:

-- Created on 2017/10/19 by ADMINISTRATOR

declare

    f boolean;

 

begin

  f:=myfunction('SMITH',30);

  if f then dbms_output.put_line('true');

  else dbms_output.put_line('false');

  endif;

 

end;

例如:定義一個函數,該函數根據員工姓名以及部門編號,查找該員工是否在emp中存在,如果存在返回true否則返回false;如果存在該員工,那么就將該條數據拿到函數外面;

createorreplacefunction myFunction(mName invarchar2,mNo innumber,msg out emp%rowType)returnbooleanis

  flag boolean:=false;

  total number;

 

begin

    selectcount(*)into total  from emp where emp.ename=mName and emp.deptno=mNo;

    if total>0then

      flag:=true;

      --將該條數據賦值給msg變量

      select emp.*into msg from emp where  emp.ename=mName and emp.deptno=mNo;

    else flag:=false;

    endif;

  return flag;

end myFunction;

測試:

declare

    f boolean;

    msg emp%rowtype;

begin

  f:=myfunction('SMITH',20,msg);

  if f then dbms_output.put_line('true');

  else dbms_output.put_line('false');

  endif;

 

  dbms_output.put_line(msg.empno||':'||msg.ename||':'||msg.hiredate);

end;

例如:定義一個函數,該函數根據員工姓名以及部門編號,查找該員工是否在emp中存在,該函數返回值為該條記錄;

createorreplacefunction myFunction(mName invarchar2,mNo innumber,msg out emp%rowType)return emp%rowtypeis

  flag boolean:=false;

  total number;

 

begin

    selectcount(*)into total  from emp where emp.ename=mName and emp.deptno=mNo;

    if total>0then

      flag:=true;

      --將該條數據賦值給msg變量

      select emp.*into msg from emp where  emp.ename=mName and emp.deptno=mNo;

    else flag:=false;

    endif;

  return msg;

end myFunction;

測試:

-- Created on 2017/10/19 by ADMINISTRATOR

declare  

    msg emp%rowtype;

begin

  msg:=myfunction('SMITH',20,msg);

  dbms_output.put_line(msg.empno||':'||msg.ename||':'||msg.hiredate);

end;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM