如何在 pl/sql 游标中生成动态位置条件



根据输入值在 pl/sql 游标中生成动态 where 条件

例如:

输入值 : a b c 值

查询格式 :

CREATE OR REPLACE Procedure abcprocedure
( a IN Number,b IN Number, c IN Number )
cursor abccursor
IS
select 1  
from pqr  p 
where ( Prepare the where condition based on a,b,c values and null checks also )

这就是我对这个问题的理解; 不需要动态的东西。

为了更简单的测试(在我这边,因为我没有你的表(,在 Scott 的DEPT表上,这可能会完成这项工作(par_x是过程参数的名称(。

select *
from dept
where deptno in (par_a, par_b, par_c)
or (par_a is null and par_b is null and par_c is null);

如果这些列不同,也没有问题:

select * 
from dept
where (deptno = par_a or par_a is null)
and (dname  = par_b or par_b is null)
and (loc    = par_c or par_c is null);

如果未传递某个参数,并且您不想看到该列的值,请使用

select case when par_a is not null then deptno
else null
end deptno,
--
case when par_b is not null then dname
else null
end dname,
--
case when par_c is not null then loc
else null
end loc
from dept
where (deptno = par_a or par_a is null)
and (dname  = par_b or par_b is null)
and (loc    = par_c or par_c is null);

如果要从结果集中排除该列,那不是那么简单。例如,如果使用了 Oracle Apex,则可以选择不呈现该列。否则,在纯SQL中,我不知道该怎么做。

根据您的评论,我应该建议在 where 条件下使用coalesce

SELECT *
FROM PQR P
WHERE COALESCE(A, DEPT1) = DEPT1
AND COALESCE(B, DEPT2) = DEPT2
AND COALESCE(C, DEPT3) = DEPT3;

如果传递的参数不为 null,Coalesce将采用该参数。这样您就可以达到预期的结果。如果 a 为 null,则dept1 = dept1将始终为真的条件(如果表中的 dept1 不为 null,则完全是另一种情况(

干杯!!

最新更新