You need to sign in to do that
Don't have an account?
SNSN
How to delete all records except one from Child Object for each Parent Object record?
Hi,
I have requirement where we have to delete all the records except one from a child object for each Parent object.
Example : Parent object : A
Child Object : B
'A' object has 1 to many relation with 'B' Object.
For each 'A' record we have to delete all the related records except one from Object 'B' . The exception record can be any record in the child object.
Can somebody help me with SOQL query for this?
Thanks in Advance,
SNSN
I have not tested the below but it should get you close.
ObjectA__c[] objA = New ObjectA__c[]{};
ObjectB__c[] tbdObjB = New ObjectB__c[]{};
objA = [Select ID, (Select ID From ObjectB__r) From ObjectA__c];
For(ObjectA A : objA){
For(ObjectB[] B : objA.ObjectB__r){
For (integer x= 1;x < B.size();x++)
tbdObjB.add(B[x]);
}
}
if (!tbdObjB.isEmpty()) delete tbdObjB;
All Answers
I have not tested the below but it should get you close.
ObjectA__c[] objA = New ObjectA__c[]{};
ObjectB__c[] tbdObjB = New ObjectB__c[]{};
objA = [Select ID, (Select ID From ObjectB__r) From ObjectA__c];
For(ObjectA A : objA){
For(ObjectB[] B : objA.ObjectB__r){
For (integer x= 1;x < B.size();x++)
tbdObjB.add(B[x]);
}
}
if (!tbdObjB.isEmpty()) delete tbdObjB;
Thank you very much for the reply!!
I used your code below with some small modifications and it worked!!