2014-10-08 27 views
0

我想從一個表作爲另一個表中的值更新特定量的總和,但得到的問題,當特定的ID沒有在另一個表存在:NHibernate的HQL子查詢:轉換零到零

的HQL我看起來像beow:

 var session = SessionManager.GetCurrentSession(); 
     var queryString = string.Empty; 

     queryString += @"update CLiner cl set cl.UnbilledDue = 
      (select sum(cu.UnbilledAmount) as UnbilledAmount from CUnbilled cu 
         where cu.AccountNo = cl.AccountNo and cu.FileDate = :fileDate) 
     where cl.FileDate = :fileDate "; 

     var query = session.CreateQuery(queryString); 
     query.SetDateTime("fileDate", new DateTime(2014, 10, 7)); 
     query.ExecuteUpdate(); 

但它給予例外時,子表中不存在特定帳戶號,並且總和返回爲零。

我試圖改變子查詢選擇到

 select isnull(sum(cu.UnbilledAmount),0) as UnbilledAmount 

其如預期不受NHibernate的HQL支持。那麼有沒有辦法,我可以在HQL的select語句轉換零到零...

+0

嘗試:coalesce(sum(cu.UnbilledAccount),0) – 2014-10-08 09:24:18

+0

非常感謝..它的工作..你可以請把它作爲答案。 – Abhijeet 2014-10-08 10:09:57

+0

親愛的,好吧,我會轉換回答;) – 2014-10-08 10:17:08

回答

0

試試這個:

coalesce(sum(cu.UnbilledAccount), 0) 

原因: 通常,當你WIRTE一個SQL查詢,以防止NULL您必須申請一個ISNULL功能在SELECT,以這樣的方式

ISNULL(SELECT sum(...., 0) or COALESCE(SELECT sum(...., 0) (return the same result but COALESCE can applied with more parameter, ISNULL has only two parameters) 

但在HQL是不可能的,所以你可以用COALESCE功能,以防止這種行爲。