存储过程

来源:互联网 发布:液压系统计算软件 编辑:程序博客网 时间:2024/05/01 06:12

存储过程是一种命名PL/SQL程序块,它可以被赋予参数,存储在数据库中,可以被用户调用。由于储存过程是已编译好的代码,所有调用的时候不用再次编译,从而提高程序的运行过程的效率,另外实现了模块化

1、 创建存储过程

语法:

Create [or replace] pricedure prcedure_name

[parameter[{in}in out}] data_type,……]

{is|as}

Decoration sectio 

Begin

 Excutable section;

Exception

Exception exception handlers;

End;

============================================================

Procduer_name 存储过程的名称

Parameter 参数

I向存储过程传递参数

Out 从存储过程返回参数

In out传递和返回参数

Data_type  :参数的类型,不呢指明长度

As|is 声明存储过程中的变量,不能用declare语句

==============================================================

例如:emp表中添加一条记录

创建存储过程

Create prcedure insert_emp as

Begin

Insert into emp(empno,ename,job,mgr,hiredate,sal,comm,deptno) values(7777,red,teacher,to_date(‘1990-09-09,yyyy-MM-dd),1000,1000,20));

Commit;

End insert_emp;

/

调用存储过程

Begin

Insert_emp;

End;

修改存储过程:就是在创建存储过程是加上or replace

Or replace

参数

Oracle中有三种参数模型in outin  out

1、 in参数

该类型的参数值是调用者传入,是默认的参数传递

Create 

1.1名称表示法

语法:

参数名称=>“参数值”,多个之间用逗号隔开

1.2位置表示法:当参数比较多时,名称表示法用的时候很繁琐,位置表示法可以简化

参数,参数。。。。。。

1.3混合表示法:是第一种和第二种表示法结合起来使用,但使用第一种表示法后,都要用第一种表示法,不能够穿插

创建

Create or replace procedure insert_into_t(p_parm in number)

   is

  begin

   insert into scott.emp(empno) values(p_parm);

  end insert_into_t;

执行

Execute insert_into_t(p_parm=>1200)

注意:

调用存储过程和函数时,参数传递有3种方式:

 按位置传递: 实参与形参依靠其排列的先后次序一一结合, 对应位置上的实参和形参相互传递数据.

 按名称传递: 使用带名的参数, 通过符号=> 连接实参和形参, 形成“ 形参名=> 实参名” 的传递方式.

 按混合方式传递: 前一部分参数的结合按位置进行, 后一部分参数的结合按名称方式进行, 但实际使用时不利于代码的阅读.

2、 Out参数:输出参数,能够由过程写入,并且可以将参数值返回给过程的调用者.

创建

Create or replace procedure emp_lookup(

 p_empno in number,

 o_ename out scott.emp.ename%type,

 o_sal out scott.emp.sal%type)

As

Begin

Select ename,sal into o_ename,o_sal from scott.emp

Where empno=p_empno;

Exception 

When no_data_found then

O_ename:=null;

O_sal:=-1;

End emp_lookup;

执行

Declare 

l_ename scott.emp.ename%type;

l_sal scott.emp.sal%type;

Begin

Emp_lookup(7782,l_ename,l_sal);//按位置传递参数

Dbms_output.put_line(ename||l_ename);

Dbms_output.put_line(sal||l_sal);

End;

3In out参数”:同时具有in参数和out参数的特性,过程可以读取参数值和写入参数值.

创建

Create or replace procedure swap(

P_parm1 in out number,

P_parm2 in out number,)

As

l_temp number;

Begin

l_temp:= P_parm1;

P_parm1:= P_parm2;

P_parm2:=l_temp;

End swap;

执行

Declare

l_num1 number:=100;

l_num2 number:=200;

Begin

Dbms_output.put_line(-----before swap------);

Dbms_output.put_line(l_num1=||l_num1);

Dbms_output.put_line(l_num2=||l_num2);

Swap(l_num1,l_num2);

Dbms_output.put_line(-----after swap------);

Dbms_output.put_line(l_num1=||l_num1);

Dbms_output.put_line(l_num2=||l_num2);

End;