Oracle學習筆記之使用者自訂函數,oracle學習筆記函數

來源:互聯網
上載者:User

Oracle學習筆記之使用者自訂函數,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;

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.