Dynamic SOQL

To create a dynamic SOQL query at runtime, use the database query method, in one of the following ways:
Return a single sObject when the query returns a single record:
    sObject S = Database.query(string_limit_1);
Return a list of sObjects when the query returns more than a single record:
    List<sObject> L = Database.query(string);
The database query method can be used wherever an inline SOQL query can be used, such as in regular assignment statements and for loops. The results are processed in much the same way as static SOQL queries are processed.


You can use simple bind variables in dynamic SOQL query strings. The following is allowed:
String myTestString = 'TestName';
List<sObject> L = Database.query('SELECT Id FROM MyCustomObject__c WHERE Name = :myTestString');

However, unlike inline SOQL, dynamic SOQL can’t use bind variable fields in the query string. The following example isn’t supported and results in a Variable does not exist error:
MyCustomObject__c myVariable = new MyCustomObject__c(field1__c ='TestField');
List<sObject> L = Database.query('SELECT Id FROM MyCustomObject__c WHERE field1__c = :myVariable.field1__c');

You can instead resolve the variable field into a string and use the string in your dynamic SOQL query:
String resolvedField1 = myVariable.field1__c;
List<sObject> L = Database.query('SELECT Id FROM MyCustomObject__c WHERE field1__c = ' + resolvedField1);

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dynamic_soql.htm



Comments

Popular posts