I have a complicated trigger that I am trying to bulkify but I don't know how to go about it. We have two main objects, Prescriptions and Study Participants. When a new Prescription is added through Informatica we have only a few pieces of information to find the right Study Participant to attach it to. We have a Participant Code (created from the first digit of first name and last digit of last name plus the day, month and year of birth) and we have a Study. Each participant can be in multiple studies so the trigger has to find the right study to attach to.
We also have an issue with the Study being wrong on some of the Prescriptions so we have to look at the fill date compared to the date enrolled for those studies.
Here is my code. It works but it hits governor limits. Any suggestions appreciated.
trigger Attach_Prescriptions on Prescription__c (before insert, before update)
{
for(Prescription__c a :Trigger.New) {
List <Study_Participant__c> TREAT2 = [select id,Name,Participant__c,Study__c, Provider__c,Study_Provider__c, Date_Enrolled__c from Study_Participant__c where Name =:a.Participant_code__c and Study__c =: 'a00A000000dMIvSIAW' and Date_Enrolled__c <:a.Fill_Date__c ];
List <Study_Participant__c> TREAT = [select id,Name,Participant__c,Study__c,Provider__c,Study_Provider__c, Date_Enrolled__c from Study_Participant__c where Name =:a.Participant_code__c and Study__c =: 'a00A000000cRWxXIAW' ];
List <Study_Participant__c> Named = [select id,Name,Participant__c,Study__c,Provider__c,Study_Provider__c, Date_Enrolled__c from Study_Participant__c where Name =:a.Participant_code__c and Study__c =:a.study__c and Study__c !=:'a00A000000cRWxXIAW' and Study__c!=:'a00A000000dMIvSIAW'];
for (Study_Participant__c d: TREAT2)
if (a.Study__c =='a00A000000cRWxXIAW' && TREAT2.size()>0 ) {
a.Patient__c=TREAT2.get(0).Participant__c;
a.Provider__c=TREAT2.get(0).Provider__c;
a.Study_Provider__c=TREAT2.get(0).Study_Provider__c;
a.Study_Participant__c=TREAT2.get(0).id;}
If(a.Study__c =='a00A000000cRWxXIAW' && TREAT2.isEmpty() && TREAT.size()>0){
a.Patient__c=TREAT.get(0).Participant__c;
a.Provider__c=TREAT.get(0).Provider__c;
a.Study_Provider__c=TREAT.get(0).Study_Provider__c;
a.Study_Participant__c=TREAT.get(0).id;
}
If(a.Study__c !='a00A000000cRWxXIAW' && Named.size()>0)// && a.Participant_code__c==d.Name && a.Study__c ==d.Study__c){
{
a.Patient__c=Named.get(0).Participant__c;
a.Provider__c=Named.get(0).Provider__c;
a.Study_Provider__c=Named.get(0).Study_Provider__c;
a.Study_Participant__c= Named.get(0).id;
}
else if (TREAT.isEmpty() && TREAT2.isEmpty() && Named.isEmpty())
{
a.Study_Provider__c = 'a05A000000Jqa3s';
a.Study_Participant__c='a02A000000DbIFn';
}
}}