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
Christina TomaselliChristina Tomaselli 

pass account field into SOQL Where clause

I am trying to write a trigger to update all the accounts with a shared field (Tax ID number) whenever any of the accounts changes. This is what I have, but am getting an error message Unexpected Token 'TIN'. 

trigger UpdateBusinessAgreement on Account (before update) {
    for (Account a : Trigger.new){
        String TIN = a.Tax_ID_Number__c;
        List<Account> matchingAccounts = [SELECT ID, Business_Agreement_Completed__c, Tax_ID_Number__c FROM Account WHERE Tax_ID_Number__c = TIN];
        if (a.Business_Agreement_Completed__c == 'Received - Complete'){
            for (Account Acc : matchingAccounts){
                Acc.Business_Agreement_Completed__c = 'Received - Complete';
                    }
        }
    }
}
Alain CabonAlain Cabon
The two points are missing before TIN.

WHERE Tax_ID_Number__c = :TIN];

https://trailhead.salesforce.com/fr/content/learn/modules/apex_database/apex_database_soql
 
Christina TomaselliChristina Tomaselli
Thanks that worked!
Christina TomaselliChristina Tomaselli
Spoke too soon, when I excute the trigger I now get a recursion error for trying to update the original trigger error. I would like to exclude the trigger record from my query by adding and AND !=: ID as below:

trigger UpdateBusinessAgreement on Account (before update) {
    for (Account a : Trigger.new){
        String TIN = a.Tax_ID_Number__c;
        String AID = a.Id;
        List<Account> matchingAccounts = [SELECT ID, Business_Agreement_Completed__c, Tax_ID_Number__c FROM Account WHERE Tax_ID_Number__c =: TIN AND ID not =: AID];
        if (a.Business_Agreement_Completed__c == 'Received - Complete'){
            for (Account Acc : matchingAccounts){
                Acc.Business_Agreement_Completed__c = 'Received - Complete';
                update acc;
                    }
        }
    }
}
Alain CabonAlain Cabon
If you want to avoid recursion there is this trick.

Apex Trigger Best practices to avoid recursion
https://help.salesforce.com/articleView?id=000332407&type=1&mode=1 (https://help.salesforce.com/articleView?id=000332407&type=1&mode=1)

Apex class: checkRecursive  (with just a class variable, only one line)
public class checkRecursive {
     Public static Boolean firstcall=false;
}
Trigger: 
if(!checkRecursive.firstcall) {
       checkRecursive.firstcall = true;
       for (Account a : Trigger.new){
           String TIN = a.Tax_ID_Number__c;
           String AID = a.Id;
           .....
}