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

标签 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

最佳答案

允许从 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

关于oracle - 从 pl/sql 中的只写(OUT)参数读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2856915/

相关文章:

database - Oracle 中的观察者模式

google-api - 如何以编程方式访问谷歌搜索右侧数据?

python - 查找句子中代词和名词之间的关系

html - 源代码顺序对可访问性有什么影响?来源顺序重要吗?

sql - 使用联接和 Group by 子句更新查询

java - 用 Java 解析数百个 pl/sql 文件

oracle - 如何执行包内的程序?

c# Entity Framework EF 4.1 在运行时更改架构和数据库名称

sql - 如果特定字段值设置为空,为什么我无法执行此插入查询?

oracle - PL/SQL FUNCTION 中的 INSERT 语句