3

Please ignore any syntax errors I may have made while typing the following up:

Schema.SObjectType t = custom__c.sObjectType;
// The following succeeds
String query = 'select id, name from ' + t + ' order by name';
List<custom__c> customs = Database.query(query);

// The following fails
query = 'select id, name from ' + t + ' where attrib__c = ' + t.substring(1,5);
List<custom__c> customs = Database.query(query);
query = 'select id, name from ' + t + ' where attrib__c = ' + t.toString().substring(1,5);
List<custom__c customs = Database.query(query);
query = 'select id, name from ' + t + ' where attrib__c = ' + ((String)t).substring(1,5);
List<custom__c> customs = Database.query(query);

I can not figure out how to obtain a substring of the sOjectType. I am using this for dynamic soql.

Is this possible?

Thanks!

2
  • Have you tried using t.getDescribe().getName()? Alternatively, since you already know the object because you're using custom__c.sObjectType, why dont use a string literal like 'Account' or 'custom__c'? Jun 4, 2013 at 19:16
  • Actually, forget that prior comment :P Since your query string is doing a comparison with a string value, you need to include the escaped single quote characters in your query, like this: ... + ' where attrib__c = \'' + t.substring(1,5) + '\'' Jun 4, 2013 at 19:19

3 Answers 3

1

Per my comment on your question, you need to include the escaped single quotation marks in your query string, like so:

query = 'select id, name from ' + t + ' where attrib__c = \'' + t.substring(1,5) + '\'';

Couldn't really answer your question if I ignored any syntax errors you made while typing your question :P

0

I'm not sure that those queries will do what you think unless you are actually storing the name of the sObject in the attrib__c field on that object for some reason but you can do the following to cast the schema type to a string and add quotes around it:

query = 'select id, name from ' + t + ' where attrib__c = \'' +  String.valueof(t).substring(1,5) + '\'';
list<custom__c> customs = Database.query(query);
0

A simple way to stringify SObjectType:

// returns 'Account' 
system.debug( Account.SObjectType + '' );                   

// returns 'Acc'
system.debug( (Account.SObjectType + '').substring(0,3) );  

// FAILS
system.debug( ((String) Account.SObjectType).substring(0,3) );  

Secondly, @Thomas Crouse answered why your SOQL statements fail.

You must log in to answer this question.

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