[英]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.