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
Nandhini S 3Nandhini S 3 

Building Dynamic SOQL query

Hi Guys,

I have a method for which redord id is the input. So based on the ID we’ll get the object type and the queries will be built dynamically based on the object type. and based on the object field names should be added to the dynamic SOQL.
Example,
Select id, name from customObject__c where customfield__c =: recordID;
 
ShivankurShivankur (Salesforce Developers) 
Hi Nandhini,

As you using this in Apex as a method with input record id, you can use following logic to get the object type:
Id myId = '0035Axxxxxxxxxxx';  // Hardcoded value for reference which will come as input to the method
String sObjName = myId.getSObjectType().getDescribe().getName();  
system.debug('Object Name is ' + sObjName);
Once you get the object type you can write a SOQL to get the fields as well.

Hope above information helps. Please mark as Best Answer so that it can help others in future.

Thanks.
 
Nandhini S 3Nandhini S 3
Hi Shivankur,

Thanks for your quick reply. I'm getting the object name by the way you have mentioned. The field in the where condition will vary based on the object. If the object is customObject1 then the field will be customfield1...for customObject2 the field will be customfield2. How can I get the fields like this.
ShivankurShivankur (Salesforce Developers) 
Hi Nandhini,

Thanks for clarifying this.

You can utilize the DescribeSObjectResult Class for this as below:
Schema.DescribeFieldResult dfr = Schema.SObjectType.Account.fields.Name;
Here in above code you will need to put the object name received from first snippet instead of Account and you can get fields specific to object found with provided record id.

Reference:
https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_sobject_describe.htm

Hope above information helps. Please mark as Best Answer so that it can help others in future.

Thanks.
Nandhini S 3Nandhini S 3
Hi Shivankur,
DescribeSObjectResult is getting the details of the field not the field name.
For now, I have written the below to get the fieldName. Instead of hardcoding the fieldName, is there any way to get the field name.
String fieldName;
        if (sObjName == 'Property__c') {
            fieldName = 'Property__c';
        }
        else if (sObjName == 'Account') {
                 fieldName = 'Account__c';
        }
        string query = 'SELECT Id, Greatest_MRI_Vacate_Date__c FROM Lease__c WHERE' + fieldName + '=: recordId';