从pl / sql中的只写(OUT)参数读取

时间:2010-05-18 11:50:17

标签: oracle plsql semantics

当我尝试写入函数的只读参数(IN)时,Oracle会抱怨错误。但是从函数的只写(OUT)参数读取时并非如此。 Oracle默默地允许这样做而没有任何错误。这种行为的原因是什么? 以下代码执行时没有对“so”变量进行任何赋值:

create or replace function foo(a OUT number) return number
  is
    so number;
  begin
    so := a; --no assignment happens here
    a := 42;
    dbms_output.put_line('HiYA there');
    dbms_output.put_line('VAlue:' || so);
    return 5;
  end;
/

declare 
  somevar number;
  a number := 6;
begin
  dbms_output.put_line('Before a:'|| a);
  somevar := foo(a);
  dbms_output.put_line('After a:' || a);
end;
/

这是我得到的输出:

Before a:6
HiYA there
VAlue:
After a:42

1 个答案:

答案 0 :(得分:6)

允许从OUT参数读取:您可以在过程开始时在OUT参数中写入内容,并且可能希望在返回之前读取它包含的值,这不是错误。

这里发生的是因为它是OUT参数而不是IN OUT参数,a的值不会传递给函数foo,所以在程序开始时OUT参数a包含NULL值。您可以通过注释掉a := 42;行:

来检查这一点
SQL> create or replace function foo(a OUT number) return number
  2    is
  3      so number;
  4    begin
  5      so := a; --no assignment happens here
  6      /*a := 42;*/
  7      dbms_output.put_line('HiYA there');
  8      dbms_output.put_line('VAlue:' || so);
  9      return 5;
 10    end;
 11  /

Function created
SQL> declare
  2    somevar number;
  3    a number := 6;
  4  begin
  5    dbms_output.put_line('Before a:'|| a);
  6    somevar := foo(a);
  7    dbms_output.put_line('After a:' || a);
  8  end;
  9  /

Before a:6
HiYA there
VAlue:
After a:
         ^^ as you can see an OUT parameter is effectively "NULLed" at the
            beginning of a call