0

I am currently developing a csv importer for our Salesforce to deal with our way of quoting items, and I am currently trying to make it so that if the product has been added in, it detects whether there's duplicate.

This is a snipped of the code i've got so far, however, the Select statement I can't seem to get working.

         for(Integer i=1; i < csvFileLines.size(); i++){
           Product2 proObj = new Product2() ;
           String[] csvRecordData = csvFileLines[i].split(',');
           proObj.name = csvRecordData[0] ;
           if([SELECT Count() FROM Product2 WHERE Name = :proObj.name[i]]==0) {                                                                                       
           productlist.add(proObj);
           }   
         }

2 Answers 2

3

If "Name" is a unique field for these records, you can use the Database class with the insert method.

insert(recordsToInsert, dmlOptions)

You can put this in a try-catch block and after enabling dmlOptions flag to allow the partial success of DML operation. This way it won't insert records that are already in the database but those that are new will successfully be inserted.

Or you can form a list of names from your CSV file, then query

[SELECT Id, Name FROM Product2 WHERE Name IN:listOfNamesFromCsv]

and then remove from your CSV-formed list of names duplicates of just use loop and check if your query has such a name, then add names to list and insert to the database by the end of the method.

P.S. Be aware of using SOQL and DML operations inside loops. This is bad practice.

1
  • 3
    Product2.Name is not a unique field in schema and sadly, you can't create Duplicate Rules on Product2 as of v48
    – cropredy
    Jun 19, 2020 at 14:40
2

This is an implementation of part of azimut3's answer (+1 there from me; didn't notice he'd described this at first glance), so FYI:

Set<String> csvNames = new Set<String>();
for (Integer i = 1; i < csvFileLines.size(); i++) {
    String[] csvRecordData = csvFileLines[i].split(',');
    String csvName = csvRecordData[0];
    csvNames.add(csvName);
}

Set<String> existingNames = new Set<String>();
for (Product2 p : [select Name from Product2 where Name in :csvNames]) {
   existingNames.add(p.Name);
}

Product2[] products = new Product2[] {};
for (Integer i = 1; i < csvFileLines.size(); i++) {
    String[] csvRecordData = csvFileLines[i].split(',');
    String csvName = csvRecordData[0];
    if (!existingNames.contains(csvName)) {
        products.add(new Product2(
            Name = csvName,
            ...
        ));
        // In case there are duplicates in the CSV; first one wins
        existingNames.add(csvName);
    }}
}
insert products;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .