I have a After insert trigger on Account which Inserts Another object (Places) after checking Account Shipping fields with Address fields of 'Places' existing Records. If nothing found it inserts Places Records.
When i am Inserting Accounts using Dataloader with few duplicates in Excel sheet. Even though i have no duplicates existing(Data base) in my Places object. It inserting Duplicate Places dueto Account Duplicates in Excel sheet
trigger InsertUniquePlaces on Account (after insert,after update) {
List<places__c> Places= new List<places__c>();
Map<Id,Account> Accounts = new Map<Id,account>();
Map<String, Id> recordTypeMap = new Map <String,Id>();
List<String> street = new List<String>();
List<String> city = new List<String>();
List<String> state = new List<String>();
List<String> zipCode = new List<String>();
List<String> country = new List<String>();
set<Id> accountIds = new set<Id>();
// After Insert
if(trigger.IsInsert&&trigger.IsAfter)
{
accounts = Trigger.newMap;
for(Account ac : accounts.Values())
{
street.add(ac.ShippingStreet);
city.add(ac.ShippingCity);
state.add(ac.ShippingState);
zipCode.add(ac.ShippingPostalCode);
country.add(ac.ShippingCountry);
}
List<Places__c> ExistingPlaces = new List<places__c>();
ExistingPlaces=[SELECT ID,Name,Street__c,City__c,State__c,
Zip__c,Country__c FROM Places__c WHERE Street__c IN : street and
City__c IN : city and State__c IN : state and Zip__c IN : zipCode and Country__c IN : country limit 50000];
if(ExistingPlaces.size()==0)
{
// If nothing Matched, Direct Insert a Loacation Record for accounts in Trigger.new
for(Account acc : accounts.Values())
{
Places__c location = new Places__c(
name = acc.Name,
Street__c = acc.ShippingStreet,
City__c = acc.ShippingCity,
State__c = acc.ShippingState,
Zip__c = acc.ShippingPostalCode,
Country__c = acc.ShippingCountry,
Location_Account__c=acc.id;
);
Places.add(location);
}
}
if(locations.size()>0 )
{
Database.Insert(Places);
//Upsert(Places);
}
Is there Any way to Avoid Duplicate records with repeated shipping address(no more name comparsion) wise at below stage before hitting database
if(locations.size()>0 )
{
Database.Insert(Places);
//Upsert(Places);
}
I dont want to Insert duplicate places even though Inserted Accounts has Duplicates. Please any one suggest me. Thanks in advance