PL/SQL基礎篇7(function,package)

 /*

  函數:可以有返回值得命名的PL/SQL子程序,必須有返回值

  關鍵字:function return

*/

-- 函數1

create or replace function helloworld

return varchar2 -- 指定返回類型,不能給定長度

as

   v_hello varchar2(50);

begin

  v_hello := 'helloworld!';

  return v_hello; --不可少的return

end;

-- 函數調用1

select helloworld from dual;

select helloworld() from dual;

-- 函數調用2

declare

   v_re varchar2(50);

begin

  v_re := helloworld(); -- 記住必須得接收函數的返回值哦

  dbms_output.put_line(v_re);

end;

--函數2

create or replace function my_func(v_sal number)

return varchar2 --一定注意,此處不能加';'

as

  v_sql varchar2(200);

  v_msg varchar2(50);

  v_min number;

  v_max number;

begin

  v_sql := 'select max(sal),min(sal) from emp';

  execute immediate v_sql into v_max,v_min;

  if v_sal > v_min and v_sal < v_max then

    v_msg := '工資在正常範圍內!';

  else

    v_msg := '不正常'; --不寫的話,在java中相當於初始化爲''

  end if;

  return v_msg;

end;

-- 調用

select my_func(1500) from dual;

declare

  v_sal number := '&薪水:';

  v_result varchar2(50);

begin

  v_result := my_func(v_sal);

  dbms_output.put_line(v_result);

end;

 

前面講了存儲過程和函數,遊標與異常,這裏開始講一個程序包

/*

  程序包:對相關存儲過程,函數,變量,遊標和異常等對象的封裝

          有聲明和主體組成

  優點:1.模塊花;2.更輕鬆的應用程序設計;3.信息隱藏;4.性能更佳

*/

-- 程序包的聲明:關鍵字:package is  end

create or replace package my_pack

as

  procedure packageTest(v_num number);

end my_pack; -- 也可以是 end;

-- 程序包的主體

create or replace package body my_pack

as

  procedure packageTest(v_num number)

  is -- as/is不能少,符合存儲過程的創建

  begin

    dbms_output.put_line(v_num);

  end;

end my_pack;

-- 程序包的調用

begin

  my_pack.packageTest(500);

end;

-- 程序包也可以只用來聲明,比如聲明一個ref遊標

create or replace package ref_pack

is

 type ref_cur is ref cursor;

end;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章