2014-02-28 60 views
0

我有一個採用可選參數的函數/過程。如果提供,我需要使用參數作爲遊標的條件。如果沒有提供,那麼我不希望這種情況。可選參數作爲遊標中的條件(PL/SQL)

下面是一個非常簡化的版本是我想出來的:

create or replace procedure check_data 
    (p_parm1 in varchar2 default null, 
    p_parm2 in number default null) 
is 
begin 
    if (p_parm1 is null && p_parm2 is null) then 
    for rec in (select col_1, col_2 
     from table_a) 
    loop 
     /*Statements, use rec.col_1 and rec.col_2 */ 
    end loop; 
    elsif (p_parm1 is null) then 
    for rec in (select col_1, col_2 
       from table_a 
       where /*condition using p_parm2 */) 
    loop 
     /*Statements, use rec.col_1 and rec.col_2 */ 
    end loop; 
    elsif (p_parm2 is null) then 
    for rec in (select col_1, col_2 
       from table_a 
       where /*condition using p_parm1 */) 
    loop 
     /*Statements, use rec.col_1 and rec.col_2 */ 
    end loop; 
    else 
    for rec in (select col_1, col_2 
       from table_a 
       where /*condition using p_parm1 */ 
        and /*condition using p_parm2 */) 
    loop 
     /*Statements, use rec.col_1 and rec.col_2 */ 
    end loop; 
    end if; 
end; 

有沒有辦法讓光標一次,表示如果不提供參數,忽略哪些條件?

回答

0

你可以讓查詢照顧所有場景中一氣呵成,如:

select col_1, col_2 
from table_a 
where (p_parm1 IS NULL OR (p_parm1 = ...)) 
AND (p_parm2 IS NULL OR (p_parm2 = ...)); 
+0

我會試試這個。我建議使用COALESCE函數,並在未提供時將變量設置爲通配符,即: v_variable1:= COALESCE(p_parm1,'%'); /*然後在where子句*/ 其中表達式LIKE v_variable1; 但這會導致需要太長時間才能返回的大規模表掃描。我的擔心是,採取所有場景的單個查詢將具有類似的性能,但我會嘗試。 謝謝! – RuinExplorer

0

也有可能是使用NVL,這是一個有點短:

select col1, col2 
from table_a 
where col1 = nvl(p_parm1,col1) 
and col2 = nvl(p_parm2,col2); 

你這樣做是什麼:當p_parm1爲空時,您將它等於條件的列(在將col1與p_parm1進行比較的情況下)。

+0

我顯然需要15點聲望投票,但這種方法確實有效。我認爲我的效率受到了很大的打擊,因爲我選擇了一種觀點,但也許我可以解決這個問題。這個概念起作用,讓我開始瞭解決方案。非常感謝! – RuinExplorer