この文章は Salesforce 機械翻訳システムを使用して翻訳されました。詳細はこちらをご参照ください。
英語に切り替える

レコードの更新/挿入

upsert 操作を使用すると、既存のレコードの挿入または更新を 1 つのコールで実行できます。レコードがすでに存在しているかどうかを確認するために、upsert ステートメントまたはデータベースメソッドは、レコードの ID をキーとして使用し、idLookup 属性が true に設定されたレコード、カスタム外部 ID 項目、または標準項目と照合します。
  • キーが一致しない場合、新規オブジェクトレコードが作成されます。
  • キーが一度だけ一致したら、既存のオブジェクトレコードが更新されます。
  • キーが複数回一致する場合は、エラーが生成され、オブジェクトレコードは挿入も更新もされません。

カスタム項目に、項目定義の一部として [ユニーク][「ABC」と「abc」を値の重複として扱う (大文字と小文字を区別しない)] 属性が選択されている場合のみ、カスタム項目による照合では大文字と小文字を区別しません。この場合、「ABC123」は「abc123」と一致します。詳細は、「カスタム項目の作成」を参照してください。

メモ

次の例では、以前 Bombay となっていた市に所在するすべての既存取引先の市の名前を更新し、さらに、San Francisco に所在していた新規取引先を挿入します。
1Account[] acctsList = [SELECT Id, Name, BillingCity
2                        FROM Account WHERE BillingCity = 'Bombay'];
3for (Account a : acctsList) {
4    a.BillingCity = 'Mumbai';
5}
6Account newAcct = new Account(Name = 'Acme', BillingCity = 'San Francisco');
7acctsList.add(newAcct);
8try {
9    upsert acctsList;
10} catch (DmlException e) {
11    // Process exception here
12}

DmlException の処理についての詳細は、「一括 DML 例外処理」を参照してください。

メモ

次の例では、Database.upsert メソッドを使用して、渡されるリードのコレクションを更新/挿入します。この例では、レコードの部分処理を許可しています。つまり、一部のレコードが処理に失敗した場合でも、残りのレコードは引き続き挿入または更新されます。また、結果を反復処理して、正常に処理された各レコードに新しい ToDo を追加します。ToDo sObject は、リストに保存され、その後一括挿入されます。この例の後に、この例をテストするテストメソッドを含むテストクラスが続きます。

1/* This class demonstrates and tests the use of the
2 * partial processing DML operations */ 
3
4public class DmlSamples {
5
6   /* This method accepts a collection of lead records and 
7      creates a task for the owner(s) of any leads that were 
8      created as new, that is, not updated as a result of the upsert
9      operation */
10   public static List<Database.upsertResult> upsertLeads(List<Lead> leads)  {
11
12      /* Perform the upsert. In this case the unique identifier for the
13         insert or update decision is the Salesforce record ID. If the 
14         record ID is null the row will be inserted, otherwise an update
15         will be attempted. */
16      List<Database.upsertResult> uResults = Database.upsert(leads,false);
17
18      /* This is the list for new tasks that will be inserted when new 
19         leads are created. */
20      List<Task> tasks = new List<Task>();
21      for(Database.upsertResult result:uResults) {
22         if (result.isSuccess() && result.isCreated()) 
23              tasks.add(new Task(Subject = 'Follow-up', WhoId = result.getId()));
24      }
25
26      /* If there are tasks to be inserted, insert them */
27      Database.insert(tasks);
28
29      return uResults;
30   }
31}
1@isTest
2private class DmlSamplesTest {
3   public static testMethod void testUpsertLeads() {
4        /* We only need to test the insert side of upsert */
5      List<Lead> leads = new List<Lead>();
6
7      /* Create a set of leads for testing */
8      for(Integer i = 0;i < 100; i++) {
9         leads.add(new Lead(LastName = 'testLead', Company = 'testCompany'));
10      }
11
12      /* Switch to the runtime limit context */
13      Test.startTest();
14
15      /* Exercise the method */
16      List<Database.upsertResult> results = DmlSamples.upsertLeads(leads);
17
18      /* Switch back to the test context for limits */
19      Test.stopTest();
20
21      /* ID set for asserting the tasks were created as expected */
22      Set<Id> ids = new Set<Id>();
23
24      /* Iterate over the results, asserting success and adding the new ID
25         to the set for use in the comprehensive assertion phase below. */
26      for(Database.upsertResult result:results) {
27         System.assert(result.isSuccess());
28         ids.add(result.getId());
29      }
30
31      /* Assert that exactly one task exists for each lead that was inserted. */
32      for(Lead l:[SELECT Id, (SELECT Subject FROM Tasks) FROM Lead WHERE Id IN :ids]) {
33         System.assertEquals(1,l.tasks.size());
34      }
35   }
36}

upsert を外部 ID と一緒に使用すると、コード内の DML ステートメントの数が減少し、ガバナ制限に該当しないようにします (「実行ガバナと制限」を参照)。この次の例では、納入商品と商談品目間の一対一の関係を維持するために、Asset オブジェクトの upsert と外部 ID 項目 Line_Item_Id__c を使用します。

このサンプルを実行する前に、Asset オブジェクト上に Line_Item_Id__c という名前でカスタムテキスト項目を作成し、外部 ID としてマークします。カスタム項目についての詳細は、Salesforce オンラインヘルプを参照してください。

メモ

1public void upsertExample() {
2    Opportunity opp = [SELECT Id, Name, AccountId, 
3                              (SELECT Id, PricebookEntry.Product2Id, PricebookEntry.Name 
4                               FROM OpportunityLineItems)
5                       FROM Opportunity 
6                       WHERE HasOpportunityLineItem = true 
7                       LIMIT 1]; 
8
9    Asset[] assets = new Asset[]{}; 
10
11    // Create an asset for each line item on the opportunity
12    for (OpportunityLineItem lineItem:opp.OpportunityLineItems) {
13
14        //This code populates the line item Id, AccountId, and Product2Id for each asset
15        Asset asset = new Asset(Name = lineItem.PricebookEntry.Name,
16                                Line_Item_ID__c = lineItem.Id,
17                                AccountId = opp.AccountId,
18                                Product2Id = lineItem.PricebookEntry.Product2Id);
19
20        assets.add(asset);
21    }
22 
23    try {
24        upsert assets Line_Item_ID__c;  // This line upserts the assets list with
25                                        // the Line_Item_Id__c field specified as the 
26                                        // Asset field that should be used for matching
27                                        // the record that should be upserted. 
28    } catch (DmlException e) {
29        System.debug(e.getMessage());
30    }
31}