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
VisithraVisithra 

Can someone help to solve dynamic soql, I have to query my sobject and its fields(ID, Name) and Where condition also dynamic SOQL and my code is below

public static void displaySobjectRecords(string objName,List<string> Fields, string field, string operator, string value){
        
        //List<string> objFields=new List<string>{'ID','Name'};
        //objFields.add('ID');
        //objFields.add('Name');
        
           String QueryStr='Select '+string.join(Fields, ',')+' From '+objName WHERE +field+' ' +operator+ ' ' +value;
        
        List<Sobject> lstObjects=Database.query(QueryStr);
        for(Sobject obj:lstObjects){
            system.debug('========');
            system.debug(obj.get('Name'));
            system.debug(obj.get('ID'));
            system.debug('========');
           
        }
        
    }

Thanks
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Visi,

Do you just need ID and Name fields from the object?

Thanks,
 
VisithraVisithra
Yes i need ID and name for condition, if needed i can also add extra fields
Eg if WHERE rating=HOT my soql query should bring all the records which is related to condition

Thanks,
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Visi,

Can you try as below.
 
public class DynamicApex {
public  void displaySobjectRecords(string objName, string field, string operator, string value){
        
        //List<string> objFields=new List<string>{'ID','Name'};
        //objFields.add('ID');
        //objFields.add('Name');
        
           String QueryStr='Select ID,NAME'+' From '+objName +' WHERE ' +field+' ' +operator +'\'' + + String.escapeSingleQuotes(value) + + '\'';
        system.debug('query'+QueryStr);
        List<Sobject> lstObjects=Database.query(QueryStr);
        for(Sobject obj:lstObjects){
            system.debug('========');
            system.debug(obj.get('Name'));
            system.debug(obj.get('ID'));
            system.debug('========');
           
        }
        
    }

}

You can execute the below in anonomous window.
 
DynamicApex DA= NEW DynamicApex();
DA.displaySobjectRecords('Account','NAME','=','Sample');

Let me know if you face any issues.

If this solution helps, Please mark it as best answer.

Thanks,