2017-09-28 38 views
0

我想用一個Map的鍵集作爲一個SQL查詢列表參數:Groovy的SQL命名列表參數

query = "select contentid from content where spaceid = :spaceid and title in (:title)" 
sql.eachRow(query, [spaceid: 1234, title: map.keySet().join(',')]) { 
    rs -> 
     println rs.contentid 
} 

我可以使用單一的值,但沒有設置或列表。 這是我到目前爲止已經試過:

map.keySet().join(',') 
map.keySet().toListString() 
map.keySet().toList() 
map.keySet().toString() 

地圖使用字符串作爲關鍵

Map<String, String> map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); 

另外,我沒有得到一個錯誤。我只是沒有打印像空白結果集。

+0

嘗試'[spaceid:1234,title:''「+ map.keySet()。join(」','「)+」'「]' – injecteer

回答

2

你appoach不會給預期的結果。

按道理你使用的是謂語,如

title = 'value1,value2,value3' 

這就是爲什麼你沒有例外,而且沒有數據的原因。

快速搜索給出了一點證據,即在Groovy SQL中可以將collectiona映射到IN列表。 請檢查herehere

所以很可能你必須定義IN列表的長度並指定你的數組中的值。

title in (:key1, :key2, :key3) 

反正這樣的事情能正常工作:

數據

create table content as 
select 1 contentid, 1 spaceid, 'AAA' title from dual union all 
select 2 contentid, 1 spaceid, 'BBB' title from dual union all 
select 3 contentid, 2 spaceid, 'AAA' title from dual; 

Groovy腳本

map['key1'] = 'AAA' 
map['key2'] = 'BBB' 

query = "select contentid from content where spaceid = :spaceid and title in (${map.keySet().collect{":$it"}.join(',')})" 
println query 
map['spaceid'] = 1 
sql.eachRow(query, map) { 
    rs -> 
     println rs.contentid 
} 

結果

select contentid from content where spaceid = :spaceid and title in (:key1,:key2) 
1 
2 

的關鍵步驟是使用表達研究map.keySet().collect{":$it"}.join(',')

注意

dynamicall準備與德綁定變量的專有名稱列表中所列您可能還需要檢查大小如果映射並處理大於1000的情況,這是單個IN列表的Oracle限制。

+0

感謝您的幫助!我不得不添加刪除空格和破折號,以使您的解決方案爲我工作 .replaceAll(「\\ s」,「」)。replaceAll(「 - 」,「」) – CaptainMango