存儲函數(shù)
- 創(chuàng)建無參存儲函數(shù)
get_name
,有返回值
語法:
create or replace function 函數(shù)名 return 返回類型 as PLSQL程序段
create or replace function get_name return varchar2
as
begin
return'哈哈';
end;
- 刪除存儲函數(shù)
getName
語法:
drop function 函數(shù)名
- 調(diào)用存儲方式一,
PLSQL
程序
declare
name varchar2(10);
begin
name:=get_name;
dbms_output.put_line('姓名是:'||name);
end;
- 調(diào)用存儲方式二,
java
程序
創(chuàng)建由有參存儲函數(shù)findEmpIncome(編號),查詢7499號員工的年收入俏险,演示in的用法,默認(rèn)in
--定義函數(shù)
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;
--調(diào)用函數(shù)
declare
income number;
begin
income:=findEmpIncome(7499);
dbms_output.put_line('該員工年收入為:'||income);
end;
--創(chuàng)建有參存儲函數(shù)findEmpNameAndJobAndSal(編號)扬绪,查詢7499號員工的姓名(return),職位(out),月薪(out),返回多個(gè)值
--創(chuàng)建函數(shù)
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;
--調(diào)用函數(shù)
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;
存儲過程:無返回值或者有多個(gè)返回值時(shí)竖独,適合用過程。
存儲函數(shù):有且只有一個(gè)返回值時(shí)挤牛,適合用函數(shù)莹痢。
適合使用過程函數(shù)的情況:
- 需要長期保存在數(shù)據(jù)庫中。
- 需要被多個(gè)用戶同時(shí)使用墓赴。
- 批操作大量數(shù)據(jù)竞膳,例如批插入多條數(shù)據(jù)。
適合使用SQL
的情況:
- 凡是上述反面诫硕,都可使用SQL坦辟。
- 對表、視圖章办、序列锉走、索引等這些,適合用SQL藕届。
向emp表中插入999條記錄挪蹭,寫成過程的形式。
--創(chuàng)建過程
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;
--調(diào)用過程
exec batchInsert;
函數(shù)版本的個(gè)人所得稅
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;
--調(diào)用過程
declare
rax number;
who number;
begin
who:=getrax(&sal,rax);
dbms_output.put_line('您需要交的稅'||rax);
end;