【问题标题】:Adding conditions to the WHERE clause in Oracle PL/SQL在 Oracle PL/SQL 中向 WHERE 子句添加条件
【发布时间】:2017-12-11 01:17:57
【问题描述】:

我正在尝试创建一个报告,允许用户通过在我的 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)) 

我简化了我的代码以确保我说得通。谁能给我一些建议?赞赏它。

【问题讨论】:

    标签: sql oracle visual-studio reporting-services parameters


    【解决方案1】:

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

    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)
    

    您可以通过包含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);/
    

    【讨论】:

      【解决方案2】:

      在阅读了这篇文章(How to handle optional parameters in SQL query?)后,我测试了以下代码,它可以工作:

      WHERE Product_No = nvl(:Product_No, Product_No)
      

      基本上,如果用户定义的值为 NULL,nvl() 将返回 Product_No。

      但是,我猜性能并未得到高度优化,因为它会检查我表中的每一行。我愿意接受任何更好的想法...

      【讨论】:

        【解决方案3】:

        我不熟悉 Oracle,但根据我将如何使用 SQL Server 进行此操作,我猜...

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-12-16
          • 2013-12-23
          相关资源
          最近更新 更多