1.存儲過程
將一段已經編譯好的代碼,封裝到數據庫中
1. 作用 :
- 提高了代碼的複用性
- 因爲以及編譯好了,可以提高了執行效率
關鍵字 - procedure /prə’siːdʒə/ 過程,程序,手續
2. 語法:
create [or replace] procedure
過程名稱(參數1 in|out 參數類型,參數2 in|out 參數類型)
is | as
-- 聲明
begin
-- 業務
end;
調用方法:
一: call 過程名稱(參數);
二: plsql中使用:
begin
過程名稱(參數);
end;
1.輸入參數
定義一個存儲過程,給員工編號爲7369的員工漲1000工資
代碼實現:
create or replace procedure
update_sal(vempno in number,vcount in number)
is
-- 聲明變量記錄當前工資
cur_sal number;
begin
-- 先查詢漲工資前的工資
select sal into cur_sal from emp where empno = vempno;
dbms_output.put_line('漲工資前: '||cur_sal);
-- 更新工資
update emp set sal = sal + vcount where empno = vempno;
-- 漲工資後的工資
dbms_output.put_line('漲工資後: '||(cur_sal+vcount));
commit;
end;
調用:
call update_sal(7369,1000);
或
begin
update_sal(7369,1000);
end;
2.輸出參數
根據員工編號,得到年薪
create or replace procedure
year_sal(vempno in number,vyearsal out number)
as
begin
select sal*12 + nvl(comm,0) into vyearsal --nvl(a,b) 如果a爲null,則取b
from emp where empno = vempno;
end;
調用:
declare
yearsal number;
begin
year_sal(7369,yearsal);
dbms_output.put_line(yearsal);
end;
3.輸出的是遊標類型:
遊標的類型是sys_refcursor
打開遊標並獲取數據一步合成:
open 遊標名 for 查詢語句
定義遊標:
create or replace procedure
findall_cursor(vcursor out sys_refcursor)
is
begin
--打開遊標,指定結果集
open vcursor for select * from emp;
end;
emp%rowtype 指的是emp的行類型
%type可以使變量獲得與字段相同的數據類型
調用
declare
yb sys_refcursor;
-- 定義一個vrow變量,類型是emp的行類型
vrow emp%rowtype;
begin
findall_cursor(yb);
loop
fetch yb into vrow;
exit when yb%notfound;
dbms_output.put_line('編號:'||vrow.empno||' 姓名:'||vrow.ename);
end loop;
-- 關閉遊標
close yb;
end;
2.存儲函數
實質是跟存儲過程一樣
和存儲過程的區別:
- 函數有返回值,過程沒有,函數的返回值可以用:=接收
- 函數可以直接在sql中調用,過程不能
- 函數和過程都實現對方的功能.
語法:
create [or replace] function
函數名稱(參數1 參數類型) return 返回類型
is
返回變量 變量類型
begin
...
return 返回變量
end;
定義一個存儲函數,根據員工編號計算一個月的納稅,稅率15%
代碼:
create or replace function
fun_getTax(vempno number) return number
is
vtax number;
begin
select sal*0.15 into vtax from emp where empno = vempno;
return vtax;
end;
調用:
declare
vtax number;
begin
vtax := fun_getTax(7369);
dbms_output.put_line(vtax);
end;