Oracle存储过程

完整的Oracle存储过程语法结构如下:

  

Create or replace procedure 过程名 as
    声明语句段;
begin
    执行语句段;
exception
    异常处理语句段;
end;

as关键词代替了无名块的declare

调用存储过程语句:

  call procedure_name();    其中()是必不可少的,无论是有参数还是没有参数

赋值语句:

  select xxx into .....或者直接  变量:=xxx

好了,下面来一个简单的例子来更好的理解存储过程

创建一个表student 

create table student(
  no number(6) primary key,
  name varchar2(25),
  age number(4)      
    
);

insert into student(no,name,age) values(1,'刘亦菲',26);
insert into student(no,name,age) values(2,'陈意涵',30);
commit;

创建一个简单的存储过程并调用
create or replace procedure stu_proc as
      p_name varchar2(25);
begin 
      select name into p_name from student where no=2;
      dbms_output.put_line(p_name);
end;

call stu_proc();

可以看到输出了 陈意涵 

上面的存储过程是一个最简单的无参数的存储过程,下面以一个有输入参数的存储过程进行演示

create or replace procedure stu_proc1(sno in student.no%type) as
       p_name varchar2(25);
begin 
       select name into p_name from student where no=sno;
       dbms_output.put_line(p_name);
end;

call stu_proc1(1);

调用stu_proc1(1)将输出 刘亦菲

-----------------------------------------------------

为了提高存储过程的健壮性,避免运行错误,当建立存储过程时应包含异常处理部分

异常(EXCEPTION)是一种PL/SQL标识符,包括预定义异常、非预定义异常和自定义异常

预定义异常是指PL/SQL提供的系统异常,非预定义异常用于处理与预定义异常无关的Oracle错误(如完整性约束等),自定义异常用于处理与Oracle错误的其他异常情况

RAISE_APPLICATION_ERROR用于自定义错误信息,并且消息号必须在-20000~-20999之间

下面通过一个简单的实例来演示

drop procedure stu_proc1;

create procedure stu_proc1(sno in student.no%type) as 
       p_name varchar2(25);
begin 
       select name into p_name from student where no=sno;
       
       exception 
              when NO_DATA_FOUND then 
              raise_application_error(-20011,'ERROR:不存在!');
       dbms_output.put_line(p_name);
end;

call stu_proc1(3);

原文地址:https://www.cnblogs.com/sstone/p/6520424.html