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
SheedSheed 

Too many SOQL queries: 101 in apex

list<HCP_User_BMS_CN__c> hcplist =[SELECT ,Hospital_Name_BMS_CN__c, Id, User_BMS_CN__r.name, Status_BMS_CN__c FROM HCP_User_BMS_CN__c  ];
for(HCP_User_BMS_CN__c hcp : hcplist){
    String hco = hcp.Hospital_Name_BMS_CN__c;
    String temp='';
    for (integer i = 0; i < hco.length(); i++) {
        temp += hco.substring(i, i+1) + '%';
    }
    String hcolike ='%'+temp ;
    
    list<Account> hcos = [SELECT Name FROM Account where  Name like: hcolike];
    list<String> hcolist = new list<String>();
    for (integer i = 0; i < hcos.size(); i++) {
        hcolist.add(hcos[i].Name);
    }
    //System.debug('hcolist'+'   '+hco+' '+hcolist.size());
    
    if(hcolist.size()>0){
        list<Account> acclist = [select id ,Name,Primary_Parent_vod__r.Name FROM Account where Primary_Parent_vod__r.Name in :hcolist and Name=:hcp.User_BMS_CN__r.name];
        if(acclist.size()>0){
           System.debug('acclist'+acclist); 
        }
    }
}

Because soql inside a for loop ,I am Getting This Below Error:System.LimitException: Too many SOQL queries: 101 . How to deal with it?
Best Answer chosen by Sheed
Niraj Kr SinghNiraj Kr Singh
Hi Zhang,

Plz find the update code here which i have corrected.
Let me know if it helps you.
/********************************************************************************************/
list<String> hcolist = new list<String>();
List<String> userBMSname = new List<String>();
list<HCP_User_BMS_CN__c> hcplist =[SELECT ,Hospital_Name_BMS_CN__c, Id, User_BMS_CN__r.name, Status_BMS_CN__c FROM HCP_User_BMS_CN__c  ];
for(HCP_User_BMS_CN__c hcp : hcplist){
    String hco = hcp.Hospital_Name_BMS_CN__c;
    String temp='';
    for (integer i = 0; i < hco.length(); i++) {
        temp += hco.substring(i, i+1) + '%';
    }
    String hcolike ='%'+temp ;
    
    list<Account> hcos = [SELECT Name FROM Account where  Name like: hcolike];
    for (integer i = 0; i < hcos.size(); i++) {
        hcolist.add(hcos[i].Name);
    }
    
    userBMSname.add(hcp.User_BMS_CN__r.name);
    
    /*
    if(hcolist.size()>0){
        list<Account> acclist = [select id ,Name,Primary_Parent_vod__r.Name FROM Account where Primary_Parent_vod__r.Name in :hcolist and Name=:hcp.User_BMS_CN__r.name];
        if(acclist.size()>0){
           System.debug('acclist'+acclist);
        }
    }*/
}

//Taken out here the code which is making error of "101"
if(hcolist.size()>0 && userBMSname.size()>0) {
    list<Account> acclist = [select id ,Name,Primary_Parent_vod__r.Name FROM Account where Primary_Parent_vod__r.Name in :hcolist and Name in:userBMSname];
    if(acclist.size()>0){
       System.debug('acclist'+acclist);
    }
}
/********************************************************************************************/
Thanks
Niraj