我可以依赖首先在 SQL 中执行的函数吗

Jac*_*las 9 oracle

请考虑以下脚本:

create or replace function f(p_limit in integer) return integer as
begin
  set_global_context ('limit', p_limit);
  return p_limit;
end;
/

create view v as 
select level as val from dual connect by level<=sys_context('global_context','limit');

select f(2), v.* from v;

/*
F(2)                   VAL                    
---------------------- ---------------------- 
2                      1                      
2                      2                      
*/

select f(4), v.* from v;

/*
F(4)                   VAL                    
---------------------- ---------------------- 
4                      1                      
4                      2                      
4                      3                      
4                      4                      
*/
Run Code Online (Sandbox Code Playgroud)

我可以依赖在f(x)视图内部读取上下文之前执行,就像在 10.2 上运行的这个测试用例一样吗?

Chr*_*xon 9

不。

如果您使用针对 where 子句(而不是 connect by)的上下文过滤重写视图,您将获得先前设置的上下文值:

create table t as 
 select rownum r from dual connect by level <= 10;

create or replace view v as 
  select r val from t where r <=sys_context('global_context','limit');

select f(2), v.* from v;

F(2) VAL
---- ---
   2   1 
   2   2 

select f(4), v.* from v;

F(4) VAL
---- ---
   4   1 
   4   2 

select f(4), v.* from v;

F(4) VAL
---- ---
   4   1 
   4   2 
   4   3 
   4   4 
Run Code Online (Sandbox Code Playgroud)

由于在选择列之前评估 where 子句,因此在读取上下文之后才会设置传递给函数的值。查询中 sys_context 调用的位置(select、where、group by 等)将准确影响设置此值的时间。