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
廣告