function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
MiddhaMiddha 

Using variable in APEX SOQL

Hi,
 
I am creating a SOQL query where the field name and the field value in where clause, both comes dynamically. Eg:
 
something like:
 
String fieldname = 'Name';
Account account = [Select Id from Acocunt where :fieldname like 'ABC'];
 
This doesnt works :(
 
Can anyone please advise, how can i get this query?
 
Thanks
[GM]
 
Ron HessRon Hess
Dynamic SOQL is not supported at this time.

You can place variables in the value, not in the field name portion of the where clause.
SiddharthSiddharth

Hi,

I am facing a similar problem and needs a work around. Actually i need to implement search option using APEX, so is it possible to use SOSL within APEX like we do it with API.

Suggestion welcomed...

 

Thanks

Siddharth

AkiTAkiT
Hi,

For adding a variable in SOQL, what is the syntax?

e.g.

var filter = 'car';
Account account = [Select Id from Account where Name like 'car%'];

That clearly is bad.

If there's a way, is it applicable for both Apex code and Ajax toolkit?

Thanks for any comment,
Aki

sfdcfoxsfdcfox
In Apex Code, you can do this:
Code:
String filter = 'car%';
Account[] Accounts = [select id from Account where Name like :filter];

 
In AJAX, you'd have to simply concatenate the values, like so:

Code:
var filter = 'car%'
sforce.connection.query('select id from account where name like \'' + filter '\'')



soofsoof
Just in case you're still looking for an answer, try DDML (Dynamic DML).  Check this out http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dynamic_dml.htm
 
I saw the link to your post somewhere else and thought I'd post a reply, just in case you still need it; otherwise, sorry to bother you!
 
-soof 
Nathan MarchantNathan Marchant
Is this still not possible in 2018??