2013-03-18 153 views
0

我试图在子查询中用case语句编写一个hql查询。子查询中的HQL case语句

select zr 
from ZipResource zr 
inner join zr.zipInflows zi 
inner join zi.toInstInflows tii 
inner join tii.toInstance ti 
where ti.state = 'COMPLETED' 
and 
ti.completedDate between :dateFrom and 
:dateTill 
and (
case when :units is not null then 
(ti.toPrototype.unit in :units) end) 
order by tii.zipInflow.zipResource.name 

这样做是真的吗?在这个查询中,我在case语句中得到了QuerySyntaxException。 任何人都可以解释我做错了什么吗?

回答

0

在你的代码:units可能是一个集(或者像这样),因为in声明需要一个集合,如果没有,它没有任何意义。但在when的条件:units is not null那里:units必须正好是一个单一值(或NULL),如果不是它是语法不正确。

如果你想检查是否:units为空,那么你需要第二个参数,例如:number_of_units,你像检查

and (
    case when :number_of_units != 0 then 
    (ti.toPrototype.unit in :units) end) 

顺便说一句,你case说法是多余的。你可以用一个简单的and条件处理它(这是值得推荐的,因为该数据库可以更好地寻找搜索索引时如何处理的条件):

and :number_of_units != 0 
and ti.toPrototype.unit in :units 

然后还有一个更简单的可能性,因为在SQL <expression> in (NULL)评估为假。只要做

and ti.toPrototype.unit in :units