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
Tom DJTom DJ 

How to convert sObject field value to a string for Dynamic SOQL query of another record.

I have trigger handler class that generically handles Lead, Contact, and Account records.   The Lead, Contact and Account triggers assign it to an sObject variable, which they pass to the trigger handler class.   The trigger takes one of the fields of the sObject (the handler decides which field by getting the field name from configuration data) and uses the value (e.g. 1223334.0) of that field to build a dynamic SOQL query.   

  Example SOQL query string:    “Select AnnualRevenue from Lead where (AnnualRevenue = 1223334.0) “

The problem I am having is how to generically turn a field value (e.g. 1223334.0) into a string no matter which data type it is.
My first solution was to do the following:

  Object myfieldvalue_object  = mySObjectRecord.get(fieldname);
  String myfieldvalue_string = (String) myfieldvalue_object;

I immediately got an exception on the second line when the object was of type DOUBLE.

My next solution was to case on the datatype of the field and cast the myfieldvalue_object as the appropriate internal data type and then turn that datatype into a string.

  if (fieldtype == Schema.DisplayType.DateTime) {
     Double convertedvalue = ((Double) myfieldvalue_object);
     String myfieldvalue_string = convertedvalue.format();
But, the converted string for a Double datatype contained commas and a decimal point (i.e the displayable value) which cannot be  used in a Dynamic SOQL query.

Given I have the field name, does anyone know how I can convert the value of a field in an sObject  to a String that can be used in a dynamic SOQL query.?    I need to be able to do it for all Object datat types with Date, Text, Number being the priority right now.

Thanks in advance.

Tom DJ


I think you are looking for the method "String.valueOf(myfieldvalue_object)" which returns doubles and dates into a format that is queryable.  The double will be returned with a period and trailing zero and no commas since that's how it is stored in SF.  But you still have the issue of adding quotes around values if you are querying against a text field.


I think the best approach is doing a describe of the field to get the datatype and do conversions based on that and then append to your query.


Hope this help.