存儲函數
- 創建無參存儲函數
get_name
,有返回值
語法:
create or replace function 函數名 return 返回類型 as PLSQL程序段
create or replace function get_name return varchar2
as
begin
return'哈哈';
end;
- 刪除存儲函數
getName
語法:
drop function 函數名
- 調用存儲方式一,
PLSQL
程序
declare
name varchar2(10);
begin
name:=get_name;
dbms_output.put_line('姓名是:'||name);
end;
- 調用存儲方式二,
java
程序
創建由有參存儲函數findEmpIncome(編號),查詢7499號員工的年收入,演示in的用法,默認in
--定義函數
create or replace function findEmpIncome(p_empno emp.empno%type) return number
as
income number;
begin
select sal*12 into income from emp where empno=p_empno;
return income;
end;
--調用函數
declare
income number;
begin
income:=findEmpIncome(7499);
dbms_output.put_line('該員工年收入為:'||income);
end;
--創建有參存儲函數findEmpNameAndJobAndSal(編號),查詢7499號員工的姓名(return),職位(out),月薪(out),返回多個值
--創建函數
create or replace function findEmpNameAndJobAndSal(p_empno in number,p_job out varchar2,p_sal out number)
return varchar2
as
p_ename emp.ename%type;
begin
select ename,job,sal into p_ename,p_job,p_sal from emp where empno=p_empno;
return p_ename;
end;
--調用函數
declare
p_ename emp.ename%type;
p_job emp.job%type;
p_sal emp.sal%type;
val varchar2(255);
begin
val:= findEmpNameAndJobAndSal(7499,p_job,p_sal);
dbms_output.put_line('7499'||p_ename||'----'||p_job||'----'||p_sal);
end;
存儲過程:無返回值或者有多個返回值時,適合用過程。
存儲函數:有且只有一個返回值時,適合用函數。
適合使用過程函數的情況:
- 需要長期保存在數據庫中。
- 需要被多個用戶同時使用。
- 批操作大量數據,例如批插入多條數據。
適合使用SQL
的情況:
- 凡是上述反面,都可使用SQL。
- 對表、視圖、序列、索引等這些,適合用SQL。
向emp表中插入999條記錄,寫成過程的形式。
--創建過程
create or replace procedure batchInsert
as
i number(4):=1;
begin
for i in 1..999
loop
insert into emp(empno,ename) values (i,'測試');
end loop;
end;
--調用過程
exec batchInsert;
函數版本的個人所得稅
create or replace function getrax(sal in number,rax out number) return number
as
--sal表示收入
--bal表示需要繳稅的收入
bal number;
begin
bal:=sal-3500;
if bal<=1500 then
rax:=bal*0.03-0;
elsif bal<4500 then
rax:=bal*0.1-105;
elsif bal<9000 then
rax:=bal*0.2-555;
elsif bal<35000 then
rax:=bal*0.3-2775;
elsif bal<80000 then
rax:=bal*0.45-5505;
else
rax:=bal*0.45-13505;
end if;
return bal;
end;
--調用過程
declare
rax number;
who number;
begin
who:=getrax(&sal,rax);
dbms_output.put_line('您需要交的稅'||rax);
end;