192k views
5 votes
How to restrict any Trigger to fire only once or avoid repeated or multiple execution of Trigger?

User Maliks
by
7.9k points

1 Answer

1 vote

Final answer:

To restrict a Trigger to fire only once, use a static variable to act as a flag to control the execution flow, preventing repeated trigger executions in a single transaction.

Step-by-step explanation:

To restrict a Trigger to fire only once and prevent multiple executions, you can utilize a static variable within a class to act as a flag. This method is often used when working with database triggers in languages such as Apex for Salesforce. Here's a step-by-step approach:

  1. Define a static variable in a separate class to keep track of whether the trigger has already run.
  2. At the start of the trigger, check the value of this static variable.
  3. If the variable indicates that the trigger has fired, use a return statement to exit the trigger without performing any operations.
  4. If the variable shows that the trigger has not yet run, set it to true and proceed with the trigger execution.

This technique ensures that even if a single transaction causes the trigger to be evaluated multiple times, it will only execute once.

User Gayan Kalhara
by
8.0k points