function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Brian Cherry FWIBrian Cherry FWI 

Bulkify Trigger Challenges

trigger NAICSUpdate on Account (before insert, before update) {
List<NAICS_Code__c> codes = [SELECT Name, Description__c from NAICS_CODE__C];
Set<NAICS_CODE__C> setcodes = new set <NaICS_code__c>();
setcodes.addAll(codes);    
for (Account acct :Trigger.new)
 {
   if(acct.NaicsCode != NULL)
   {
       try {
     string twoDigit =  acct.NaicsCode.left(2);
     string threeDigit =  acct.NaicsCode.left(3);
     NAICS_Code__c nCode2desc = [SELECT Name, Description__c from NAICS_CODE__C where Name = :twoDigit limit 1]; 
     NAICS_Code__c nCode3desc = [SELECT Name, Description__c from NAICS_CODE__C where Name = :threeDigit limit 1]; 
     acct.NAICS_2_Digit_Desc__c = nCode2desc.Description__c;
     acct.NAICS_3_Digit_Desc__c = nCode3desc.Description__c;           
}
       catch (Exception e) {
           system.debug('Failed');
       }
   }
       
     
     
 }
}

I'm trying to remove the two queries in the for loop. I can't use a map since I'm searching by name and not ID. I'm not really sure how to utilize set to return the right description if I use contains. Any help would greatly be appreciated.
 
Best Answer chosen by Brian Cherry FWI
ZhixunZhixun
put the name in your map as key , and the sObject as value.

All Answers

ZhixunZhixun
put the name in your map as key , and the sObject as value.
This was selected as the best answer
Brian Cherry FWIBrian Cherry FWI
Duh.... Thanks!!!
Brian Cherry FWIBrian Cherry FWI
Just in case someone else has this problem:
 
trigger NAICSUpdate on Account (before insert, before update) {
Map<String, String> codemap = new Map<String, String>();
    for(NAICS_Code__c codes : [SELECT Name, Description__c from NAICS_CODE__C]) {   
codeMap.put(codes.name, codes.description__c);
    }    
for (Account acct :Trigger.new)
 {
   if(acct.NaicsCode != NULL)
   {
       try {
     string twoDigit =  acct.NaicsCode.left(2);
     string threeDigit =  acct.NaicsCode.left(3); 
     acct.NAICS_2_Digit_Desc__c = codeMap.get(twoDigit);
     acct.NAICS_3_Digit_Desc__c = codeMap.get(threeDigit);          
}
       catch (Exception e) {
           system.debug('Failed');
       }
   }
          
 }
}