0

I have read here that bind variables can be used in dynamic SOQL (which I am aware of) But on the code:

List<sObject> testQuery = Database.query('SELECT id from Account where Name = :a.Name');

It says that variable does not exist.

Though I know the workaround to put that in the string with the binding of the variable then pass in the whole string in the query.

Question is when does it became a "Bind Variable Field" and when does it became a "Bind Variable"

1 Answer 1

1

Bind variable: you have a local primitive data type variable and you want to bind its value. I.E.

Integer quantity = 10;
Database.query('SELECT AccountId FROM Asset WHERE Quantity =: quantity');

Bind variable fields: you have a complex object, like a custom type or a SObject, and you want to bind the value of its property. In this case you must declare a variabile of the correct primitive data type assinging the value you want to bind. I.E.

Account acc = ...;
String industry = acc.Industry;
Database.query('SELECT FirstName, LastName FROM Contact WHERE Account.Industry =: industry');

Keep in mind that the variable you want to bind must have a local scope.
Not Allowed:

Database.query('SELECT Id FROM Account WHERE Name =: SomeClass.SOME_CONSTANT');

Allowed:

String name = SomeClass.SOME_CONSTANT;
Database.query('SELECT Id FROM Account WHERE Name =: name');
2
  • So If I actually have an Account, and I use :account_somefield. That is actually a bind variable field. If I use string x = account_somefield. and used that string x in the query that is actually a bind variable. Correct?
    – Snorlax
    Dec 2, 2022 at 13:21
  • 1
    @Tachzxc That's right, indeed with :account.xyz__c you're trying to bind a field (xyz__c) of a variable (account).
    – RubenDG
    Dec 2, 2022 at 13:41

You must log in to answer this question.

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