目录

SOQL for循环

当我们不想创建List并直接迭代SOQL查询的返回记录集时,将使用这种类型的for循环。 我们将在后续章节中研究有关SOQL查询的更多信息。 现在,只需记住它返回查询中给出的记录和字段列表。

语法 (Syntax)

for (variable : [soql_query]) { code_block }

OR

for (variable_list : [soql_query]) { code_block }

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

流程图 (Flow Diagram)

Apex For Loop

例子 (Example)

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

// 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);
↑回到顶部↑
WIKI教程 @2018