oracle 存储过程
存储过程
定义:将常用的或很复杂的工作,预先用SQL语句写好并用一个指定的名称存储起来, 那么以后要叫数据库提供与已定义好的存储过程的功能相同的服务时,只需调用execute,即可自动完成命令。
存储过程的优点:
1.存储过程只在创造时进行编译,以后每次执行存储过程都不需再重新编译,而一般SQL语句每执行一次就编译一次,所以使用存储过程可提高数据库执行速度。
2.当对数据库进行复杂操作时(如对多个表进行Update,Insert,Query,Delete时),可将此复杂操作用存储过程封装起来与数据库提供的事务处理结合一起使用。
3.存储过程可以重复使用,可减少数据库开发人员的工作量
4.安全性高,可设定只有某此用户才具有对指定存储过程的使用权
存储过程创建语法:
create or replace procedure 存储过程名(param1 in type,param2 out type)
as
变量1 类型(值范围);
变量2 类型(值范围);
Begin
Select count(*) into 变量1 from 表A where列名=param1;
If (判断条件) then
Select 列名 into 变量2 from 表A where列名=param1;
Dbms_output。Put_line(‘打印信息’);
Elsif (判断条件) then
Dbms_output。Put_line(‘打印信息’);
Else
Raise 异常名(NO_DATA_FOUND);
End if;
Exception
When others then
Rollback;
End;
注意事项:
1, 存储过程参数不带取值范围,in表示传入,out表示输出
2, 变量带取值范围,后面接分号
3, 在判断语句前最好先用count(*)函数判断是否存在该条操作记录
4, 用select 。。。into。。。给变量赋值
5, 在代码中抛异常用 raise+异常名
create or replace package body TestPackage is procedure UpdateRecords(id_in in number, newName in varchar2, newAgein number) as begin update test set age = newAge, name = newName where id = id_in; end UpdateRecords; procedure SelectRecords(ret_cursor out mycursor) as begin open ret_cursor for select * from test; end SelectRecords; procedure DeleteRecords(id_in in number) as begin delete from test where id = id_in; end DeleteRecords; procedure InsertRecords(name_in in varchar2, age_in in number) as begin insert into test values (test_seq.nextval, name_in, age_in); --test_seq是一个已建的Sequence对象,请参照前面的示例 end InsertRecords; end TestPackage;
页:
[1]