Apex - SOQL For Loop

Esse tipo de forloop é usado quando não queremos criar a lista e iterar diretamente sobre o conjunto de registros retornado da consulta SOQL. Estudaremos mais sobre a consulta SOQL nos capítulos subsequentes. Por enquanto, basta lembrar que ele retorna a lista de registros e campo conforme fornecido na consulta.

Sintaxe

for (variable : [soql_query]) { code_block }

ou

for (variable_list : [soql_query]) { code_block }

Uma coisa a notar aqui é que o variable_listou a variável deve ser sempre do mesmo tipo que os registros retornados pela Consulta. Em nosso exemplo, é do mesmo tipo que APEX_Invoice_c.

Diagrama de fluxo

Exemplo

Considere o seguinte for loop exemplo usando SOQL for ciclo.

// 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);