2017-02-10 58 views
0

我需要使用的情況下,當生成函數的值範圍(在DB2中)。
例如,在下面的代碼,我想在(5,6)使用'case when'後功能

select columnA from tableName where columnB in (
    (case 
    when @variable=1 then '4' // specific number 
    when @variable=2 then '5' //specific number 
    when @variable=3 then '7,10' // a value range 
    end) 
) 

的columnB但試了幾次和其他類似的解決方案,從來沒有得到預期的結果

如何做到這一點?

+0

爲什麼? 1 = 1也總是如此。請解釋你正在嘗試做什麼 – GurV

+0

tks for ur reply,改進了我的曲線 –

回答

1

首先,In函數不讀取Case語句中的多個值。逗號必須在範圍內的每個單值之後。

其次,你可以在你的問題中提到一個有效的條件,而不僅僅是1=1。它總是如此,沒有道理。

實施例:下面的查詢
1)輸出給in (5, 6)

select columnA from tableName where columnB in ((case when @variable=1 then 5 end), 6); 

2)此僅給出columnB = 5的記錄,讓說第二條件是false

select columnA from tableName where columnB in ((case when @variable=1 then 5 end), (case when @variable=2 then 6 end)); 
+0

@SamualLee,當然,這是在'IN'函數內使用例子的方式。 – Vikrant

0

嘗試這樣的事情

select columnA from tableName 
where columnB in (       
    select * from table(values 4) tmp(NewCol)  
    where @variable=1 
    union all 
    select * from table(values 5) tmp(NewCol)  
    where @variable=2 
    union all 
    select * from table(values 7, 10) tmp(NewCol)  
    where @variable=3          
)             
0

你不能有字符串值範圍內,除非你將其轉換爲行集。我不確定如何在DB2中做到這一點,但我有一些應該工作的東西,因爲根據文檔,DB2確實有unnest()。當然還有其他創建行集的方法。

SELECT columnA 
    FROM unnest(array[2,6,8,10], array[7,5,6,28]) --create "temp table" for example purposes 
    WITH ORDINALITY AS a(columnA, columnB) --alias columns from temp table 
WHERE 
    CASE WHEN true THEN --switch true to some other condition 
    columnB IN(SELECT * FROM unnest(array[5,6])) --unnest(array[]) will create rowset with 2 rows, each having one column holding integer value 
    END; 

您可能需要從AS a(columnA, columnB)下降別名,因爲我不知道它是否工作在DB2中,我還沒有發現活的DB2測試儀(它需要在PostgreSQL中,我測試了查詢)。