存儲(chǔ)過程和存儲(chǔ)函數(shù)指存儲(chǔ)在數(shù)據(jù)庫中供所有用戶程序調(diào)用的子程序叫存儲(chǔ)過程或者存儲(chǔ)函數(shù)泰演;
存儲(chǔ)過程和存儲(chǔ)函數(shù)
相同點(diǎn):完成特定功能的任務(wù)肮韧;
不同點(diǎn):是否用return語句返回值
存儲(chǔ)過程不能通過return返回一個(gè)函數(shù)子句悯周,存儲(chǔ)函數(shù)通過return返回一個(gè)函數(shù)子句,引入Out函數(shù)后勺鸦,存儲(chǔ)函數(shù)可以用存儲(chǔ)過程替代,存儲(chǔ)函數(shù)只能有一個(gè)返回值妇萄,存儲(chǔ)過程可以有多個(gè)返回值蜕企,因?yàn)橐蛳录嫒荩設(shè)racle升級(jí)的時(shí)候保留了存儲(chǔ)函數(shù)冠句;
create [or replace] procedure sayhelloworld
as
begin
dbms_output.put_line('Hello_world');
end;
/
調(diào)用存儲(chǔ)過程的方法:
第一種:
exec.sayhelloworld;
第二種:
begin
sayhelloworld;
sayhelloworld;
end;
/
創(chuàng)建帶參數(shù)的存儲(chǔ)過程轻掩,如給指定的員工漲100元,并打印漲前和漲后的工資
create or replace procedure raisesalary(eno in number)
as psal emp.sal%type
begin
select sal from emnp where empno=eno;
update emp set sal=sal+100 where empno=eno;
dbms_output.put_line('漲前:' ||psal||' '漲后:' ||cpsal+100));
end;
/
因?yàn)榇鎯?chǔ)過程是子程序懦底,所以內(nèi)部的update操作不建議用commit和rollback唇牧;
創(chuàng)建存儲(chǔ)函數(shù)的語句
create [or replace] function 函數(shù)名(參數(shù)列表)
return 函數(shù)值類型
as
PLSQL 子程序體
如存儲(chǔ)函數(shù)->查詢某個(gè)員工的年收入
create or replace function queryempincome(eno in number) //in代表輸入?yún)?shù)
return number
as
//定義保存變量員工的薪水和獎(jiǎng)金
psal emp.sal%type;
pcomm emp.comm%type;
begin : //得到該員工的悅心和獎(jiǎng)金
select sal,comm into psal,pcomm from emp where empno=eno;
return psal*12 + nvl(pcomm,0);
end;
/
out表示輸出參數(shù)
如查詢某個(gè)員工的姓名,月薪和職位
create or replace procedure queryempinform(eno in number,
pname out varchar2,
psal out number,
pjob out varchar2)
as
begin
select ename,sal,empjob into pename,psal,pjob from emp where empno=eno;
end;
/
創(chuàng)建JDBC的連接方式
driver;url;user,password;
Class.forName(driver);
driver.getConnection();
CallableStatement call = conn.prepareCall(sql);
call.setInt(1,7839);
call.registerOutParameter(2,OracleTypes.VARCHAR);
call.registerOutParameter(2,OracleTypes.NUMBER);
call.execute();
call.getDouble(3);
call.getString(4);
Out光標(biāo)
創(chuàng)建包頭
create or replace package mypackage as
type empcursor is ref cusor;
procedure queryEmpList(dno in number, empList out empcursor);
end mypackage;
創(chuàng)建包體,包體內(nèi)實(shí)現(xiàn)包頭的所有聲明
create or replace package body mypackage as
procedure queryEmpList(dno in number, empList out empcursor) as
begin
//打開光標(biāo)
open empList for select * from emp where deptno=dno;
end queryEmpList;
end mypackage;