【问题标题】:Using a CASE WHEN statement in NHibernate HQL在 NHibernate HQL 中使用 CASE WHEN 语句
【发布时间】:2020-02-20 10:06:42
【问题描述】:

我的查询

select oc.Id as Id, (CASE WHEN (select Count(Id) from CompanyAuthorizedInfo cai where cai.Company.Id = oc.Id and cai.IsDefault = 1 and cai.Status=1) = 1 THEN (select MAX(cai2.Name) from CompanyAuthorizedInfo cai2 where cai2.CompanyId = oc.Company.Id and cai2.IsDefault = 1 and cai2.Status=1) ELSE MAX(aut.Name) END) as AuthorizedName , MAX(oc.CustomerRepresentative.Id) as CustomerRepresentativeId, MAX(oc.RecordDate) as RecordDate, MAX(oc.TpeOwnerCode) as TpeOwnerCode, MAX(oc.CodeAttorney) as CodeAttorney, oc.Name as Name, (select c.Name  from City c where  c.Id=MAX(oca.City.Id)) as CityName, (select d.Name  from District d where  d.Id=MAX(oca.District.Id)) as DistrictName, MAX(aut.PhoneNo) as PhoneNo ,MAX(cif.Number) as PhoneNumber, MAX(oc.Email) as Email, (select u.Name+' '+u.Surname from Users u where u.Id = MAX(oc.CustomerRepresentative.Id)) as CustomerRepresentativeName, MAX(CASE WHEN oc.HaveACustomer=1 THEN 1 ELSE 0 END) as IsCustomer , MAX(CASE WHEN oc.HaveACustomer=1 THEN 'Müşteri' WHEN oc.HaveAPotantialCustomer=1 THEN 'Potansiyel Müşteri' ELSE 'Firma' END) as CustomerStatus from Company oc left join oc.Addresses oca with oca.Status = 1 left join oc.AuthorizedInfos aut with aut.Status = 1 left join oc.ContactInfos cif with cif.Status = 1 and cif.ContactType.Id < 4 where oc.Status = 1 and oc.UserCompany.Id = :userCompanyId group by oc.Id, oc.Name order by oc.Name asc

条件在查询中运行时,then 语句中的字段返回错误。然后,当我在 SQL 中而不是查询中编写一个固定值(如 1-2)时,它就可以工作了。

我得到的错误是

QuerySyntaxException 未被用户代码处理

【问题讨论】:

  • 是 SQL 还是 HQL?
  • 子查询输出不能是聚合函数的参数。请改用THEN SELECT MAX(tbl2.Name) AS Name ...
  • 请添加错误信息。
  • @Mukul QuerySyntaxException 未被用户代码处理
  • 这不能是 SQL 查询的整个文本。这在语法上是不正确的 - 此代码可以是查询文本的一部分,也可以是复合结构(函数、过程等)中的语句。

标签: sql nhibernate hql case-when


【解决方案1】:

不要将聚合函数 MAX 应用于整个选择查询,而是尝试将其应用于“tbl2.Name”列。

请参阅以下更新后的查询。

(   CASE WHEN 
        (   select  Count(Id) 
            from    TableName tbl 
            where   tbl.Company.Id = oc.Id 
            and     tbl.IsDefault = 1 
            and     tbl.Status=1
        ) = 1 
    THEN 
        select  MAX(tbl2.Name) 
        from    CompanyAuthorizedInfo tbl2 
        where   tbl2.CompanyId =c.Company.Id 
        and     tbl2.IsDefault = 1 
        and     tbl2.Status=1
    ELSE 
        MAX(aut.Name) 
    END
) as Value

【讨论】:

  • 不工作。同样的错误。用户代码未处理 NullReferenceException,用户代码未处理 QuerySyntaxException
猜你喜欢
  • 2021-09-13
  • 2012-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多