存儲過程
存儲過程實際上是封裝在伺服器上的一段PLSQL代碼片段(已經編譯好了的代碼)。使用者通過指定存儲過程的名字并給出參數(如果該存儲過程帶有參數)來執行它。
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnL1YTN1UDMwIjMwEzNwAjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
建立一個給某個員工加特定工錢的存儲過程:
-- empid是使用者輸入的指定的員工id
-- insal是使用者輸入的指定的漲薪多少
-- currentsal是員工漲薪錢的目前工資
create or replace procedure cc1(empid in number,insal in number)
is
currentsal number;
begin
select sal into currentsal from emp1 where id=empid;
dbms_output.put_line('his sal before is '||currentsal||'$');
update emp1 set sal=sal+insal where id=empid;
dbms_output.put_line('his sal after is '||(insal+currentsal)||'$');
commit;
end;
存儲過程的調用
-- 第一種
call 存儲過程名(參數1, 參數2···);
-- 第二種
declare
begin
存儲過程名(參數1, 參數2···);
end;
call cc1(1005,3000);
存儲函數
存儲函數和存儲過程基本都差不多,隻是存儲函數有傳回值,存儲過程沒有。
存儲函數的調用
declare
變量1 類型;
begin
變量1:=存儲函數名(參數1,參數2···);
dbms_output.put_line(變量1);
end;
範例:
建立一個查詢某個員工的年薪的存儲函數:
-- 輸入參數的in辨別可以省略
create or replace function emptotalsal(empid number) return number
is
fullyearsal number;
begin
select sal*12+nvl(bonus,0) into fullyearsal from emp1 where id=empid;
return fullyearsal;
end;
-- 調用存儲函數emptotalsal
declare
e number;
begin
e:=emptotalsal(1007);
dbms_output.put_line(e);
end;