+ Start a Discussion
Krishna Prasad K PKrishna Prasad K P 

How will my trigger (after insert/update) behave for UPSERT operation

Hi All,
I have a trigger on Opportunity with "before Insert and Before Update"   trigger_events.
The code snippet is given below.

for(Opportunity myOpp : trigger.new)
           {
                  if((Trigger.isUpdate)&&(someother condition))
                            //statements_1
                else if(Trigger.isInsert)
                            //statements_2                                            
          }

In most of the cases,Opportunities are inserted/updated in Bulk using Apex DataLoader.    
  1. If I use UPSERT opertion using DataLoader, will that cause my records to escape from both the IF statements  ??  
  2. Does each record has seperate value for "Trigger.isUpdate" and "Trigger.isInsert" implicit variables??
  3. While UPSERTing using DataLoader, if my first set of values causes an UPDATE and the second causes an INSERT, what would be the values of  Trigger.isUpdate and Trigger.isInsert ??
Please help me to clarify these doubts..

Thanks in Advance,
Krishna
nikolanikola
Krishna,

Here is my take on this:

  1. No. At least one if statement will be called. See item 3 for more explanation.
  2. No. Trigger.isUpdate and Trigger.isInsert is set once per trigger execution.
  3. Upsert statement is different then other statements (insert, update, delete, undelete) in that it's executed as two statements. So the trigger from your example will get called twice: once for inserted records and once for updated records.
Try this in a development instance:

Code:
trigger UpsertTrigger on Opportunity (before insert, before update) {
  double rnd = Math.random();
  for( Opportunity opt : Trigger.new )
  {
     opt.rnd__c = rnd;
  }

}

 Then use data loader to upsert two records: a new record that will be inserted and another one that will be updated. You will notice (if all goes well) that the two random numbers are different. Hence, the trigger is executed twice.

I hope this example helps (although it probably wasn't very hard for you to create it yourself).

Regards,