如何在 APEX 中创建具有不同 SOQL 的列表集合

How to create List collection with different SOQLs in APEX

我有一个 APEX 触发器,它在插入后触发。假设通过 SOQL select 机会并将其分配给列表集合。 但是List和SOQL依赖于另一个变量Vehicle_Type__c。下面的代码不起作用,我收到错误“PulledOpportunities”变量不存在。

if ( l.Vehicle_Type__c != 'Truck' ) {


List<Opportunity> PulledOpportunities = [SELECT Id, Name FROM Opportunity WHERE StageName =: 'Active' AND Med_Expiration__c >=: System.TODAY() AND Opp_Record_Type_ID__c =: 'ABC' AND WareHouse__c IN: WarehouseList];

} else {


List<Opportunity> PulledOpportunities = [SELECT Id, Name FROM Opportunity WHERE StageName =: 'Active' AND Opp_Record_Type_ID__c =: 'ABC' AND WareHouse__c IN: WarehouseList];

}

Integer FoundOpportunities = PulledOpportunities.size();

有什么建议可以让它发挥作用吗? 谢谢

if/else 构造之外声明变量 PulledOpportunities。您的变量被限定在它们最近的封闭块(花括号)内,因此当 if 结束时它们会超出范围。

List<Opportunity> PulledOpportunities;

if ( l.Vehicle_Type__c != 'Truck' ) {
    PulledOpportunities = [SELECT Id, Name FROM Opportunity WHERE StageName = 'Active' AND Med_Expiration__c >=: System.TODAY() AND Opp_Record_Type_ID__c = 'ABC' AND WareHouse__c IN: WarehouseList];
} else {
    PulledOpportunities = [SELECT Id, Name FROM Opportunity WHERE StageName = 'Active' AND Opp_Record_Type_ID__c = 'ABC' AND WareHouse__c IN: WarehouseList];
}

Integer FoundOpportunities = PulledOpportunities.size();

另请注意,您应该只在与 Apex 变量进行比较的地方使用 : 绑定运算符。 'Active' 等静态值不需要也不应使用绑定符号。