Oracle中存储过程的使用


一 存储过程的基本应用

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 out number) 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"。

相关内容