1、使用過程或函數的好處
1)確保數據安全性:例如,現有一個過程能夠更新某數據表,管理員不必授予用戶直接訪問數據表的權限,而是授予用戶訪問此過程的權限。
2)提升性能:使用存儲過程時通過網絡傳輸的數據量較小,減少網絡傳輸量。
3)減少內存:存儲過程可以利用 Oracle 的共享內存特性,多個用戶執行同一個過程時只需將一份過程副本加載到內存中。通過在多個用戶間共享相同的代碼,能夠顯著地減少應用程序所需的 Oracle 內存。
4)開發完整性,及提高開發效率。
2、兩者的相同及不同點
1)函數必須有一個返回值(return type),而過程不必。
2)函數可以單獨執行,如:Dbms_Output.put_line('5+6='||tAdd(5,6));--tAdd是一個函數
而過程不可以;
3)函數可以嵌入到SQL語句中執行,而過程不能。如:select my_pak.tAdd(1,2) from dual;
4)兩者的輸入參數類型都是in,out,in out,默認都是in。
3、函數例子
--定義函數
create or replace function NumAdd(num1 number,num2 number,num3 out number)return number
as
num number;
begin
num3:=num1-num2; --out 參數的傳出參數
num:=num1+num2;
return num; --return 參數
end;
--使用函數返回值
declare
num number;
num2 number;
begin
num:=NumAdd(5,2,num2);
dbms_output.put_line('num='||num); --結果爲:7
dbms_output.put_line('num2='||num2); --結果爲:3
end;
3、過程例子
3.1 無參無返回值的存儲過程
--無參無返回值的存儲過程
create or replace procedure pro_test
as
begin
dbms_output.put_line('無參,無返回值的存儲過程');
end;
--使用
declare
begin
pro_test;
end;
3.2 有返回值的存儲過程
--通過輸入班級號cid,返回該班最大年齡的姓名maxAgeName,及全部人員c_stuList
create or replace procedure pro_test(cid varchar2,maxAgeName out student.name%type
,c_stuList out sys_refcursor)
as
c_stu sys_refcursor;
type record_stu is record(
tname student.name%type,
tage student.age%type
);
re_stu record_stu;
ageTemp student.age%type;
nameTemp student.name%type;
begin
open c_stu for select name,age from student where classid=cid;
c_stuList:=c_stu; --因爲在過程中要使用c_stu,使用後無數據,所以...
ageTemp:=0;
loop
fetch c_stu into re_stu;
exit when c_stu%notfound;
dbms_output.put_line('name='||re_stu.tname||' age='||re_stu.tage);
if ageTemp<re_stu.tage then
ageTemp:=re_stu.tage;
nameTemp:=re_stu.tname;
end if;
end loop;
maxAgeName:=ageTemp;
end;
--調用存儲過程
declare
c_stu sys_refcursor;
maxAgeName student.name%type;
tname student.name%type;
tage student.age%type;
begin
pro_test('C001',maxAgeName,c_stu);
dbms_output.put_line('最大人年齡是'||maxAgeName);
loop
fetch c_stu into tname,tage;
exit when c_stu%notfound;
dbms_output.put_line('name='||tname||' age='||tage);
end loop;
end;
轉載自:
http://www.cnblogs.com/lovemoon714/archive/2012/03/01/2375172.html