0

I am trying to use like operator in like query using Ajax toolkit, but unable to do so.

I am trying this:

var att_name = '%sample%';
var result = sforce.connection.query("select id, from Attachment where name like " + att_name);

Any help would be truly appreciated.

4 Answers 4

2

String literal values in SOQL and SOSL query WHERE clauses, including ordinary strings, picklist value API names, email addresses, IDs etc., must always be enclosed in (single) quotes, except in the case of using binding variables in Apex. This is mentioned in the documentation:

You must supply a value whose data type matches the field type of the specified field. You must supply a native value—other field names or calculations are not permitted. If quotes are required (for example, they are not for dates and numbers), use single quotes. Double quotes result in an error.

It is for this reason adding single quotes makes this query work.

1
  • Thank you for the clarification.
    – Badar
    Commented Dec 7, 2020 at 10:12
1

This should work:

    var att_name = '%sample%';
    var result = sforce.connection.query("select id from Account where name like " + "'" + att_name + "'");
3
  • Thanks bro, I already found the fix and solved it.
    – Badar
    Commented Dec 7, 2020 at 9:00
  • your answer has an extra , after id. You will have to remove it otherwise it will throw malformed query. Commented Dec 7, 2020 at 9:02
  • Oh, you are right. The same syntax problem is in question too. My bad, I didn't notice.
    – Badar
    Commented Dec 7, 2020 at 10:11
1

I would use Javascript template literals:

`select id from Account where name like '%${att_name} %'`

Notice the backticks ` used to wrap the string.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

It keeps the code clean and makes it easy to maintain.

0

Fixed, this worked for me:

var att_name = '%sample%';
var result = sforce.connection.query("select id, from Attachment where name like'" +att_name + "'");
0

You must log in to answer this question.

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