You need to sign in to do that
Don't have an account?

FIELD_INTEGRITY_EXCEPTION, This price definition already exists in this price book
My requirement is to take any pricebook entry made in the standard pricebook and replicate/update it in a second price book. With the code below I keep getting the error below. I have read everything I could find, but I cannot figure out what I need to change.
FIELD_INTEGRITY_EXCEPTION, This price definition already exists in this price book: []Also, I need the logic to look and see if the pricebookentry (product2Id) already exists and if so, just update the unitprice. But anytime I add that logic I get too many SOQL queries. (I was adding a query to look up the pricebookentries in the second price book, with an if statement to see if the product2id already existed. I had it in the for loop of the code below. - so 2 for loops and an if statement. It was the only way I could figure out how to get the logic, and obviously it was not correct.) Any help would be much appreciated.
global class pricebookEntryCopybatch implements Database.Batchable<sObject>{ public final string query; Set<Id> pbeIds = new Set<Id>(); Pricebook2 stdPrice = [Select id, isActive from Pricebook2 where isStandard=true limit 1]; Pricebook2 fdaPrice = [Select id, isActive from Pricebook2 where Name='FDA Pricebook' limit 1]; global pricebookEntryCopybatch(){ query = 'Select Id, Pricebook2Id, isActive, SystemModStamp from PriceBookEntry '; } global Database.querylocator start(Database.BatchableContext BC){ return Database.getQueryLocator(query); } global void execute(Database.BatchableContext BC, List<sObject> scope){ for(sObject s : scope){ for(PricebookEntry pbe : (List<PricebookEntry>)scope){ if(pbe.Pricebook2Id == stdPrice.Id && pbe.IsActive == true && pbe.SystemModStamp > Datetime.now().addMinutes(-15)){ pbeIds.add(pbe.id); } } List<PricebookEntry> pbeforinsert = new List<PricebookEntry>(); system.debug('***************************************stdPrice ' +stdPrice); system.debug('***************************************fdaPrice ' +fdaPrice); List<PricebookEntry> stdPBE = [SELECT Pricebook2Id, IsActive, UnitPrice, Id, Product2Id, CurrencyIsoCode FROM PricebookEntry Where Id in: pbeIds]; for(PricebookEntry pbecopy : stdPBE){ PricebookEntry pbesToAdd = new PricebookEntry();{ pbesToAdd.Pricebook2Id = fdaPrice.Id; pbesToAdd.IsActive = pbecopy.IsActive; pbesToAdd.Product2Id = pbecopy.Product2Id; pbesToAdd.UnitPrice = pbecopy.UnitPrice; pbesToAdd.CurrencyIsoCode = pbecopy.CurrencyIsoCode; pbeforinsert.add(pbesToAdd); } } insert pbeforinsert; } } global void finish(Database.BatchableContext BC){ } }

This was answered on the stackexchange: https://salesforce.stackexchange.com/questions/215924/field-integrity-exception-this-price-definition-already-exists-in-this-price-bo/215926#215926