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
Rafi Hoq 4Rafi Hoq 4 

how to insert variable into queried string

I'm querying for my message's body text. Example - 'Hi my name '+testName+' how are you' 

That string is a text field on the message object. What do I need to do in the code to make those variables work? This string needs to be queried from the object, not hardcoded in the code.

 
Best Answer chosen by Rafi Hoq 4
David Zhu 🔥David Zhu 🔥
String formattedString = String.format('Hi my name is {0}, how are you?', new String[]{'David Zhu'});
System.debug(formattedString);

All Answers

VinayVinay (Salesforce Developers) 
Hi Rafi,

Try below snippet.
String field = 'fieldx__c';
Strign soqlQuery = 'select Id,'+field+',Name from object__c';
object__c obj = database.query(soqlQuery);

Review below links which gives you more information.

https://developer.salesforce.com/forums/?id=906F00000008z5BIAQ
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SOQL_variables.htm

Hope above information was helpful.

Please mark as Best Answer so that it can help others in the future.

Thanks,
Vinay Kumar
David Zhu 🔥David Zhu 🔥
String formattedString = String.format('Hi my name is {0}, how are you?', new String[]{'David Zhu'});
System.debug(formattedString);
This was selected as the best answer
Varun Sharma 150Varun Sharma 150

Hi
seems you are trying to build dynamic query. YOu can do that by first fetching the value in a variable;

List< SelectedPropName> data= [Select SelectedPropName from SettingsObject LIMIT 1];
if(data!=null && data.size()>0
{
string SelectedProeprty = data[0].SelectedPropName;

if(SelectedPropName!=null && SelectedPropName.trim().length >0)
{

string SOQL = string.Format("Select {0} from MasterObject", new List<object> {SelectedPropName});
Object Result = Database.Query(SOQL);

}

}

Hope above information was helpful.

Please mark as Best Answer so that it can help others in the future.

Thanks,
Varun Sharma
varun.y.sharma@gmail.com