3

I'm working on some systems integration pieces and as part of it I've written a trigger to automatically determine the related campaign based on the criteria entered. This all works small scale but I need some help fixing it for bulk uploads.

It's specifically causing too many SOQL calls due to the fact my query is inside of the loop. I just can't seem to wrap my head around a way to accomplish this without doing it like this. Any expertise would be greatly appreciated.

trigger WebInt_CampaignRelation on Website_Interaction__c (before insert) {
   for (Website_Interaction__c wi : trigger.new){
       string campname = wi.Campaign__c +'- '+wi.utm_content__c +' '+ wi.utm_source__c;
       map<ID, Campaign> flatcmp = new map<ID, Campaign>([select Id from Campaign where Name = :campname]);
       for (Campaign cmp : flatcmp.values()){
          wi.SFCampaign__c = cmp.ID;
     }
}

}

Edit: Here's what I ended up with. I successfully did a bulk test of 200 records with only 3 SOQL calls.

trigger WebInt_CampaignRelation on Website_Interaction__c (before insert) {
map<ID, Campaign> cmp = new map<ID, Campaign>([select Id, name from Campaign]);
for (Website_Interaction__c wi : trigger.new){
    string campnameconst = wi.Campaign__c +'- '+wi.utm_content__c +' '+ wi.utm_source__c;
    for (Campaign cmps : cmp.values()){ 
        If(cmps.Name == campnameconst){
            wi.SFCampaign__c = cmps.ID;
        }
    }
}

}

1 Answer 1

5

You need to create a set containing all the campname strings before running your query. Your code should look more like this:

trigger WebInt_CampaignRelation on Website_Interaction__c (before insert) {
   set<string>campnames = new set<string>();
   string campname;

   for (Website_Interaction__c wi : trigger.new){
       campname = wi.Campaign__c +'- '+wi.utm_content__c +' '+ wi.utm_source__c;
       campnames.add(campname);
   }

   map<ID, Campaign> flatcmp = new map<ID, Campaign>([select Id from Campaign where Name = :campnames]);
   for (Campaign cmp : flatcmp.values()){
      wi.SFCampaign__c = cmp.ID;
   }
}
1
  • You gave me a bump in the right direction.
    – bcarlock
    Feb 26, 2015 at 19:26

You must log in to answer this question.

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