2017-09-28 42 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