2013-03-18 155 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