Apex - SOQL For 循环
当我们不想创建 List 并直接迭代 SOQL 查询返回的记录集时,可以使用这种类型的 for 循环。 我们将在后续章节中详细研究 SOQL 查询。 现在,只需记住它返回查询中给定的记录和字段列表。
语法
for (variable : [soql_query]) { code_block }
or
for (variable_list : [soql_query]) { code_block }
这里需要注意的一件事是,variable_list 或变量应始终与查询返回的记录具有相同的类型。 在我们的示例中,它与 APEX_Invoice_c 具有相同的类型。
流程图
示例
考虑以下使用 SOQL for 循环的 for 循环 示例。
// 使用 For SOQL 循环的相同先前示例 List<apex_invoice__c> PaidInvoiceNumberList = new List<apex_invoice__c>(); // 初始化要存储的自定义对象记录列表 // 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]) { // 该循环将迭代并处理查询返回的每条记录 if (objInvoice.APEX_Status__c == 'Paid') { // 检查上下文值中当前记录的条件 System.debug('Value of Current Record on which Loop is iterating is '+objInvoice); //循环正在迭代的当前记录 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);