Pergunta

I've read thread from 2005 and people said SOQL does not support string concatenation.

Though wondering if it is supported and someone has done this.

I'm trying to concat but no luck :(

Below is APEX code trying to find record with specified email.

String myEmail = 'my@email.com';
String foo = 'SELECT emailTo__c, source__c FROM EmailLog__c 
              WHERE source__c = \'' +
              myEmail + '\';

Database.query(foo)

Even though the record is indeed in the database, it does not query anything. Debug shows "row(0)" which means empty is returned.

Am I doing concat wrong way?

UPDATE

I just found a way not have to add single quote. Just needed to apply same colon variable even for String that has query.

String foo = DateTime.newInstance(......);

String bar = 'SELECT id FROM SomeObject__c WHERE createdOn__c = :foo';

List<SomeObject__c> result = Database.query(bar);

System.debug(result);

This works too and is necessary if WHERE clause contains DateTime since DateTime cannot be surrounded with single quotes.

Foi útil?

Solução

Why do you use Database.query()? Stuff will be much simpler and faster if you'll use normal queries in brackets

[SELECT emailTo__c, source__c FROM EmailLog__c WHERE source__c = :myEmail]

Not to mention that parameter binding instead of string concatenation means no need to worry about SQL injections etc.. Please consider getting used to these queries in brackets, they look weird in beginnign but will save your butt many times (mistyped field names etc).

As for actual concatenation - it works like you described it, I'm just unsure about the need to escape apostrophes. Binding the variables is safest way to go.

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dynamic_soql.htm http://www.salesforce.com/us/developer/docs/api/index_Left.htm#CSHID=sforce_api_calls_soql.htm|StartTopic=Content%2Fsforce_api_calls_soql.htm|SkinName=webhelp

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top