在 Oracle PL/SQL 中向 WHERE 子句添加条件

蓝鲸

我正在尝试创建一个报告,允许用户通过在我的 Oracle PL/SQL 中Product_No添加一个参数来过滤掉他们想要查看的产品我正在使用与 Oracle 数据库连接到我的报告的 SQL Server Reporting Services。

我的挑战是,如果用户没有输入任何Product_No,那么我的报告应该返回所有产品。

虽然Product_No已经在我的 SELECT 子句中,但我觉得在 WHERE 子句中添加一些条件应该可行。

但是我的代码出了点问题,如果我不输入Product_No,它会返回 NULL (如果我输入 Product_No,那么它可以工作):

select Product_No, Product_Name
from Product_Table
where (:Product_No is null) OR
     ((:Product_No is not null) AND Product_No IN (:Product_No)) 

我简化了我的代码以确保我有意义。谁能给我一些建议?赞赏它。

巴巴罗斯·欧占

你可以创建一个基于函数的索引

create index idx_prod_no on Product_Table (nvl2(Product_No,1,0));

并运行统计打包索引生效:

exec dbms_stats.gather_table_stats(myschema,'Product_Table',cascade=>true);

并使用此 where 条件来提高性能:

where nvl2(Product_No,1,0) = nvl2(:Product_No,1,0)

您可以使用包括execution plan测试它以显示index usage

SQL>set autotrace on;
SQL>var Product_No number; -- to see the results for NULL values
SQL>select Product_No, Product_Name
     from Product_Table
    where nvl2(Product_No,1,0) = nvl2(:Product_No,1,0);/

SQL>var Product_No number=1; -- to see the results for Product_No = 1 (as an example)
SQL>select Product_No, Product_Name
     from Product_Table
    where nvl2(Product_No,1,0) = nvl2(:Product_No,1,0);/

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章