繁体   English   中英

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

[英]Adding conditions to the WHERE clause in Oracle PL/SQL

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

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

尽管Product_No已经在我的SELECT子句中,但是我觉得在WHERE子句中添加一些条件应该可以。

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

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)) 

我简化了代码以确保我说得通。 有人可以给我一些建议吗? 赞赏。

阅读本文( 如何处理SQL查询中的可选参数? )后,我测试了以下代码,并且可以正常工作:

WHERE Product_No = nvl(:Product_No, Product_No)

基本上,如果用户定义的值为NULL,则nvl()将返回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 nvl2(Product_No,1,0) = nvl2(:Product_No,1,0)

您可以通过包括显示index usage execution plan来对其进行测试:

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);/

我对Oracle不熟悉,但是根据我将如何使用SQL Server来做,我猜...

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM