Apex-soql-for-loop

提供:Dev Guides
移動先:案内検索

Apex-SOQL Forループ

このタイプの for ループは、リストを作成せず、SOQLクエリの返されたレコードのセットを直接反復処理する必要がない場合に使用されます。 SOQLクエリについては、以降の章で詳しく説明します。 現時点では、クエリで指定されたレコードとフィールドのリストを返すことを覚えておいてください。

構文

for (variable : [soql_query]) { code_block }

or

for (variable_list : [soql_query]) { code_block }

ここで注意すべきことの1つは、 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);