2016-09-08 24 views
-3

編寫下面的代碼給我錯誤說:條件串狀的sprintf

PL/SQL:語句被忽略 PLS-00382:表達式類型錯誤:

代碼:

if (l_vol = 0) 
    then 
     l_cndtn_string := 'l_wgt > l_wgt_limit';    
    else 
     l_cndtn_string := '(l_wgt > l_wgt_limit) and (l_vol > l_vol_limit)'; 
    end if; 

    if (l_cndtn_string) 
    then 
     l_isis_task := 'PO'; 
    else 
     l_isis_task := 'TO'; 
    end if; 

回答

0

If statement評估了boolean expression。在您的例子

if (l_cndtn_string) 

l_cndtn_string不是布爾表達式而是character expression且兩者之間沒有隱式轉換。

請幫助自己,並檢查Expressions了。

我不知道什麼是你的邏輯,但下面的示例顯示字符表達式轉換成布爾表達式的一種方式:

if l_cndtn_string is not null -- a boolean expression 
then 
    null; 
else 
    null; 
end if; 
0

你要動態條件構建。與其他編譯語言一樣,plsql很難做到。

嘗試這樣的:IF布爾表達式的預期,而不是一個字符串

if (l_vol = 0) 
then 
    if(l_wgt > l_wgt_limit) then 
     l_isis_task := 'PO'; 
    end if;   
else 
    if(l_wgt > l_wgt_limit and l_vol > l_vol_limit) then 
     l_isis_task := 'TO'; 
    end if; 
end if; 
0

之後 - 這就是爲什麼你得到PLS-00382錯誤。當然,你可以嘗試使用動態SQL動態地評估你的表現,但事實上,你想要什麼的很簡單:

if (l_wgt > l_wgt_limit and (l_vol = 0 or l_vol > l_vol_limit)) 
then 
    l_isis_task := 'PO'; 
else 
    l_isis_task := 'TO'; 
end if; 
0

哦,只有在閱讀其他的答案後,我意識到這是什麼問題是什麼。我決定也保留我的原始答案,因爲關於if語句中的字符表達的觀點仍然正確。

其他答案是正確的,建立一個基於字符串評估與動態PL/SQL邏輯通常不是一個好主意。他們也提出正確的解決方案,但恕我直言更好的方法存在。

通常當我在PL/SQL中有多個條件時,我給條件一個名字。請參閱下面的示例說明該技術。這些名稱使得代碼自我記錄,並且在代碼可讀性方面有了巨大的提高,因爲現在的條件通常是人類語言。

declare 
    v_volume number := 0; 
    v_weight number := 1; 

    v_weight_limit constant number := 10; 
    v_volume_limit constant number := 10; 

    v_has_volume constant boolean := v_volume > 0; 
    v_exceed_weight_limit constant boolean := v_weight > v_weight_limit; 
    v_exceed_volume_limit constant boolean := v_volume > v_volume_limit; 
begin 
    -- no guarantee the logic is the same than in question 
    -- but just illustrates the coding style 
    if v_has_volume 
    and v_exceed_weight_limit 
    and v_exceed_volume_limit 
    then 
    null; -- something 
    else 
    null; -- something else 
    end if; 
end; 
/