I have tried upserting PriceBookEntry

PricebookEntry p = new PricebookEntry();
List<PricebookEntry> lstp = new List<PricebookEntry> {};
 Pricebook2 pb = [select Id, IsActive from PriceBook2 where IsStandard=True];
 PricebookEntry sp = new PricebookEntry();

                                    p.product2id = '01t28000001rYB5';
                                    p.pricebook2id = '01s28000009KhaR';
                                    p.UnitPrice= 110.08;

upsert lstp;

Note: For the first time it is inserting correctly. But for the next time when I run this program, it is showing the below error message as

System.DmlException: Upsert failed. First exception on row 0; first error: DUPLICATE_VALUE, This price definition already exists in this price book: []

Am I doing anything wrong?? Or else Suggest me if there any other possible way to upsert PriceBookEntry.

  • Try to upsert like this - upsert lstp {externalid/matchingid field name};
    – MIX DML
    Jul 17 '16 at 7:35
  • I have already tried your suggestion... the same error captured Jul 17 '16 at 7:46
  • System.DmlException: Upsert failed. First exception on row 0; first error: INVALID_FIELD_FOR_INSERT_UPDATE, Unable to create/update fields: Product2Id. Please check the security settings of this field and verify that it is read/write for your profile or permission set.: [Product2Id] Jul 17 '16 at 8:00
  • You can apply the suggestion mention in the following link : salesforce.stackexchange.com/questions/73881/…
    – MIX DML
    Jul 17 '16 at 9:15

In order to upsert an sObject you'll need the objects Id or another external key field. Some options to achieve what you want:

  • Create a external Id field and populate it with a unique combination of fields (example: Product2Id + Pricebook2Id) and use that field on your upsert call upsert lstp New_External_Field__c
  • Query for Pricebook entry and retrieve the Id if they exist. And set it on the object you're trying to upsert

In the Pricebookentry, Pricebook2Id and Product2Id are unique combination, so can't be modified.

You can delete an entry and can add new entry

  • Yes Santanu that is correct. Upvoting your answer. Dominic once you delete old entry you could upsert new entry based on any created external id. Jul 17 '16 at 13:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.