I ran into this exception while trying to make some dynamic SOQL queries(also SOSL but haven't gotten to test those yet).

Basically I'm trying to build a query string and add a dynamic value as one of the parameters. Problem is I don't know what type that value will be(string, integer, etc). I don't think I can manually cast to all possible types, I'm looking for a more elegant solution.
Code in question:

qryHolder = 'SELECT {0} FROM {1} WHERE {0} =: val';

Where val is String val = String.valueOf(sobj.get(fieldName.getName())); sobj is a random sobject, fieldName is Schema.DesribeFieldResult.
I can also make something like

'SELECT {0} FROM {1} WHERE {0} = {2}' 

And {2} would be val but then it doesn't work for Strings and only work for Numbers.
Any solution to this?

1 Answer 1


Bind to an Object.

Then you can set values which will work for a number field:

Object val = 42;

Or a text field:

Object val = 'Some text';

And so on.

  • 1
    Yup - tested it after posting and wanted to come here to post the answer. You beat me to it. :)
    – stefan
    Feb 21, 2018 at 13:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .