5

When I run the below code, I get this error:

no viable alternative at character '\'

Code:

public void getChildRecords() {
    DescribeSObjectResult describe = objectVar.getSObjectType().getDescribe();

    childRelationshipNames = new List<String>();

    for (Schema.ChildRelationship child:describe.getChildRelationships()) {
        childRelationshipNames.add(child.getRelationshipName());
    }

    String relationshipQuery = 'SELECT ';

    for (String relationship:childRelationshipNames) {
        if (relationship != 'null' && relationship != null) { 
            relationshipQuery += '(SELECT Id, FirstName, LastName, Email, Salary__c FROM ' + relationship + '), ';
        }
    }

    relationshipQuery += 'Id,  FirstName, LastName, Email, Salary__c FROM ' + describe.getName() + ' WHERE ID = \'' + objectVar.Id + \'' ';

    objectVar = Database.query(relationshipQuery);
}
4
  • 6
    You need to do this Id = \'' + objectVar.Id +'\'' Jul 6, 2016 at 13:19
  • 1
    You can use bind in dynamic query so you should only need ' where Id = :objectvar.id '
    – Eric
    Jul 6, 2016 at 13:50
  • 2
    @Eric - No dot notation in dynamic binds - :objectId works but object.id won't. see developer.salesforce.com/docs/atlas.en-us.apexcode.meta/…
    – cropredy
    Jul 6, 2016 at 14:31
  • 2
    Personally I'd stick to the : notation and just have a local ID type variable equal to objectVar.Id. Easier to type correctly and read and a habit that avoids injection attack risk for cases where that could arise.
    – Keith C
    Jul 6, 2016 at 14:59

1 Answer 1

8

As noted in the comments, you've escaped the wrong single quote.

Incorrect

'WHERE Id = \'' + someId + \'' '

Correct

'WHERE Id = \'' + someId + '\''

Also noted in the comments, you can use bind variables if you cache the Id itself as a top level property.

Id someId = objectVar.Id;
objectVar = Database.query('SELECT ... FROM ... WHERE Id = :someId');

You must log in to answer this question.

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