You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Salesforce Apex动态SOQL用==触发QueryException报错如何解决?

问题原因

SOQL语法的等值判断仅支持单个等号=,不支持Apex原生代码中常用的双等号==,你在else分支的查询条件中写了Region__r.Id == :selectedRegion,双等号不属于SOQL的合法运算符,因此触发了语法报错。

修复方案

把else分支SOQL语句中的==替换为=即可,修改后的完整代码如下:

String FullQuery = '';
if(selectedRegion == 'All'){
    FullQuery = 'select Id, Name, Region__r.Id, Region__r.Name, CreatedDate from Country__c where Id in (select country_link__c from Market__c where Focus_Year__c = True)';
} else {
    // 仅将此处的==修改为=即可解决报错
    FullQuery = 'select Id, Name, Region__r.Id, Region__r.Name, CreatedDate from Country__c where Id in (select country_link__c from Market__c where Focus_Year__c = True) and Region__r.Id = :selectedRegion';
}
List<Country__c> RelevantCountryList2 = Database.query(FullQuery);
System.debug(RelevantCountryList2);

额外注意事项

  • Apex代码自身的逻辑判断用==,但拼接的SOQL字符串属于SOQL语法体系,所有等值判断都要使用单个=,二者规则不通用,动态拼接SOQL时要注意区分
  • SOQL的不等值判断用!=,该规则和Apex语法一致,仅等值判断存在差异

内容的提问来源于stack exchange,提问作者Ben2pop

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 15:18:01