Apex - SOQL for 循环



当我们不想创建列表并直接迭代 SOQL 查询返回的记录集时使用这种类型的 for 循环。我们会在后续的章节中详细了解 SOQL 查询。现在,只需记住,它会返回查询中给定的记录和字段列表。

语法

for (variable : [soql_query]) { code_block }

for (variable_list : [soql_query]) { code_block }

这里需要注意的一点是,variable_list 或变量应该始终与查询返回的记录类型相同。在我们的示例中,它与 APEX_Invoice_c 相同类型。

流程图

Apex For Loop

示例

考虑使用 SOQL for 循环的以下 for 循环示例。

// The same previous example using For SOQL Loop
List<apex_invoice__c> PaidInvoiceNumberList = new
List<apex_invoice__c>();   // initializing the custom object records list to store
                           // the Invoice Records
List<string> InvoiceNumberList = new List<string>();

// List to store the Invoice Number of Paid invoices
for (APEX_Invoice__c objInvoice: [SELECT Id,Name, APEX_Status__c FROM
   APEX_Invoice__c WHERE CreatedDate = today]) {
   
   // this loop will iterate and will process the each record returned by the Query
   if (objInvoice.APEX_Status__c == 'Paid') {
      
      // Condition to check the current record in context values
      System.debug('Value of Current Record on which Loop is iterating is '+objInvoice);
      
      //current record on which loop is iterating
      InvoiceNumberList.add(objInvoice.Name);
      // if Status value is paid then it will the invoice number into List of String
   }
}

System.debug('Value of InvoiceNumberList with Invoice Name:'+InvoiceNumberList);
apex_loops.htm
广告