一 存儲過程的基本應用
1 創建存儲過程(SQL窗口)
create or replace procedure update_staff
as
begin
update staff set name = 'xy';
commit;
end update_staff;
存儲過程適合做更新操作,特別是大量數據的更新
2 查看存儲過程在數據字典中的信息(SQL窗口)
select object_name,object_type,status from user_objects where lower(object_name) = 'update_staff'
3 查看存儲過程語句(SQL窗口)
select * from user_source where lower(name) = 'update_staff'
4 執行存儲過程(Command窗口)
execute update_staff;
5 存儲過程的優點
① 提高數據庫執行效率。使用SQL接口更新數據庫,如果更新復雜而頻繁,則需要頻繁得連接數據庫。
② 提高安全性。存儲過程作為對象存儲在數據庫中,可以對其分配權限。
③ 可復用性。
二 帶輸入參數的存儲過程
1 創建存儲過程(SQL窗口)
create or replace procedure update_staff(in_age in number) as
begin
declare newage number;
begin
newage := in_age + 10;
update staff set age = newage;
commit;
end;
end update_staff;
2 執行存儲過程(Command窗口)
execute update_staff(10);
3 默認值
只有in參數可以有默認值,比如
create or replace procedure update_staff(in_name in varchar2,in_age in number default 20)
調用時可只寫execute update_staff('xy');
三 帶輸出參數的存儲過程
1 創建存儲過程(SQL窗口)
create or replace procedure update_staff (in_age in number,out_age outnumber) as
begin
update staff set age = in_age;
select age into out_age from student where num = 1;
commit;
end update_staff;
存儲過程沒有顯示制定返回值,但輸出參數可以輸出
2 輸出存儲過程結果(Command窗口)
set serverout on;
declare age number;
begin
update_staff(20,age);
dbms.output.put_line(age);
end;
四 帶輸入輸出的存儲過程
其中最典型的應用是交換兩個數的值
1 創建存儲過程(SQL窗口)
create or replace procedure swap (param1 in out number, param2 in out number) as
begin
declare param number;
begin
param:=param1;
param1:=param2;
param2:=param;
end;
end swap;
2 輸出存儲過程結果(Command窗口)
set serverout on;
declare p1 number:= 25;
p2 number:=35;
begin
swap(p1,p2);
dbms_output.put_line(p1);
end;
五 參數總結
①輸入參數:有調用者傳遞給存儲過程,無論存儲過程如何調用該參數,該參數的值都不能被改變,可以認為該參數的值是只讀的。
②輸出參數:可以作為返回值來用。可以認為可寫。
③輸入輸出參數:這中類型的參數和java方法中的參數最像,傳入方法,可讀可寫(final標識符除外)。
④參數順序總結如下:具有默認值的參數應該位于參數列表的末尾,因為有時用戶需要省略該參數。沒有默認值的參數可以遵循"in -> out -> in out"。