[SalesForce] no viable alternative at character ‘%’ in dynamic soql

I am creating this dynamic query and I am getting this error

String qry = '[Select id, name From selectedObject Where selectedField LIKE : '%' + userInput + '%' ]';

Best Answer

This isn't a "dynamic" query. A dynamic query is one that has variable fields, objects, or filter conditions. Unless you have a strong, compelling reason, simply use an inline query:

SOject[] results = [Select id, name From selectedObject Where
                    selectedField LIKE :'%'+userInput+'%'];

Alternatively, you can use binding directly, but you'll have to modify your input string:

String selectedFieldValue = '%'+userInput+'%';
String query = 'SELECT Name FROM selectedObject WHERE '+
               'selectedField LIKE :selectedFieldValue';

This avoids the need to use String.escapeSingleQuotes, so the code is a bit more legible. There are restrictions on how bind expressions work in dynamic queries; the variable must be accessible to the current function, and must be a simple variable (i.e. not part of an array, etc).