Apex - SOQL per loop

Questo tipo di forloop viene utilizzato quando non si desidera creare l'elenco e iterare direttamente sul set di record restituito dalla query SOQL. Studieremo di più sulla query SOQL nei capitoli successivi. Per ora, ricorda che restituisce l'elenco dei record e dei campi come indicato nella query.

Sintassi

for (variable : [soql_query]) { code_block }

o

for (variable_list : [soql_query]) { code_block }

Una cosa da notare qui è che il file variable_listo la variabile deve essere sempre dello stesso tipo dei record restituiti dalla query. Nel nostro esempio, è dello stesso tipo di APEX_Invoice_c.

Diagramma di flusso

Esempio

Considera quanto segue for loop esempio utilizzando SOQL for ciclo continuo.

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