+ Start a Discussion
SunnyShinySunnyShiny 

SOQL Apex code > string

Hello,

 

I dont know the right way to write down this

 

String val = 'Saler';

 

I tried >
String soqlQuery = 'Select id  from Contact  Where RecordType.Name = ' + 'Saler' + ' limit 1';

 

>

String soqlQuery = 'Select id  from Contact  Where RecordType.Name = ' + val + ' limit 1';
system.debug(soqlQuery);

 

But quotes disapears, how can I do ?

 

Thanks

sfdcfoxsfdcfox

You can use:

 

String val = 'Saler';
String soqlQuery = 'SELECT Id FROM Contact WHERE RecordType.Name = :val LIMIT 1';

This assumes that "val" will still be in scope when Database.query(soqlQuery) is called.

 

If this is not the case, use the following type of design:

 

String val = 'Saler';
String soqlQuery = String.format(
  'SELECT Id FROM Contact WHERE RecordType.Name = \'\'{0}\'\' LIMIT 1',
  new string[] { String.escapeSingleQuotes(val) });

This uses String.format and String.escapeSingleQuotes to properly create the dynamic SOQL string.