电脑技术学习

Oracle概念:过程、函数、程序包

dn001

  OUT 参数:

  从过程向调用者返回值:

  例子:使用scott.emp表,编写搜索过程,输入empno,返回ename , sal

  分析:

  desc scott.emp

  参数:一个in, 两个out

  参数类型:in number, out emp.ename%type , out emp.sal%type

  con scott/tiger

  create or replace

  procedure emp_lookup(

  p_empno in number,

  o_ename out emp.ename%type ,

  o_sal out emp.sal%type) as

  begin

  select ename, sal

  into o_ename, o_sal

  from emp

  where empno= p_empno;

  exception

  when NO_DATA_FOUND then

  o_ename := ‘null’;

  o_sal := -1;

  end;

  /

  执行该过程:

  1. 使用匿名PL/SQL

  分析:目的是输出两个out参数的结果,所以匿名块中也要定义2个与out参数相同的局域变量。

  set serveroutput on

  declare

  l_ename emp.ename%type;

  l_sal 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;

  /

  2. 在sql plus 中执行

  分析:需要使用sql plus 的VARIABLE命令绑定参数值,即为OUT参数提供接受返回值的变量。

  Variable name varchar2(10);

  Variable sal number;

  Exec emp_lookup(‘7782’, :name, :sal);

  Print name;

  Print sal;

  Select :name, :sal from dual;

  IN OUT 参数:

  可以用来传入参数,并从存储过程返回值。

  例子:输入两个数,交换值

  思路:通过一个临时变量作为交换过程中的过渡

  create or replace

  procedure swap(

  p1 in out number,

  p2 in out number ) as

  l_temp number; --局域变量的声明,相当于匿名块中declare之后的声明;过程:as~begin

  begin

  l_temp := p1;

  p1 := p2;

  p2 := l_temp;

  end swap;

  /

  set serveroutput on

  declare

  l1 number:=100;

  l2 number:=200;

  begin

  swap(l1,l2);

  dbms_output.put_line(‘l1 = ‘|| l1);

  dbms_output.put_line(‘l2 = ‘|| l2);

  end;

  /

  关于自主事务处理: P197

  我们曾经讨论过COMMIT 和 ROLLBACK的概念。

  建立过程P2:

  CREATE OR REPLACE PROCEDURE P2 AS

  A varchar2(50);

  Begin

  Select venadd1 into a from vendor_master where vencode=’V002’;

  Dbms_output.put_line(a);

  ROLLBACK;

  END;

  /

  建立过程P1,调用P2:

  CREATE OR REPLACE PROCEDURE P1 AS

  B varchar2(50);

  Begin

  Update vendor_master set venadd1=’10 Walls Street ‘ where vencode=’V002’;

  P2();

  Select venadd1 into b from vendor_master where vencode=’V002’;

  Dbms_output.put_line(b);

  ROLLBACK;

  END;

  /

  exec p1

  说明事务处理可以跨越过程继续执行。

标签: 函数