Ask Search:
Chirag VermaChirag Verma 

how to get particular record id in For each loop

I have given a interview and interviewer ask me to write a trigger with this condition:

to do the work same as roll-up summary in contacts to capture the age from all the contacts related to a particular account. so i write this trigger.....but he said that at (line 4) for all the different contacts related to different account, your code will add the age of all the contacts related to that account or not to the a single account record not to the designated account related records.

So i have to ask that, how should we differentiate at (line 5) to add the contacts age for that particular Account only.

Trigger abc on Contact (before insert, before update){
        List<Account> a1 = [Select name,Tage from Account where id];
        For(Account aa1: a1){
            aa1.Tage =+[0].age;
        }update aa1 or update a1;
        List<Account> a2 = [Select name,Tage from Account where id];
        For(Account aa2: a2){
            If( !=Trigger.old.age){
            aa2.Tage =- Trigger.old[0].age;    
            aa2.Tage =+[0].age;
        }update aa2 or update a2; 

Kindly reply as early as possible as i have to go back there tomorrow for same Interview.

Chirag Verma
Best Answer chosen by Moderator ( 
Maria BelliMaria Belli
You may want to try posting your question at one of the following sites that are geared more toward developers: