System.LimitException: Too many SOQL queries: 101
Triggers are executed before or after records of a particular type are inserted, updated, or deleted from the Force.com platform database.
Before writing a trigger a requirement must
be clear on which type of operation a trigger needs to run.
The following are the best practices with Example:
·
Minimizing the number of data
manipulation language (DML) operations by adding records to collections and
performing DML operations against these collections.
· Minimizing the
number of SOQL statements by preprocessing records and generating sets, which
can be placed in single SOQL statement used with the IN
clause
Use of List ,Set and Maps helps avoiding
governer Limit Exceptions.
The below code is not considered as a good
code as it will eventually hit governor limits.
for (Account a : trigger.new)
{
for (Contact c : [select
id,otherphone from contact where accountid = :a.id]) {
c.OtherPhone= a.Phone;
update c;
|
Good practice using List,Maps and Sets.
Set<ID> ids = Trigger.newMap.keySet();
List<Account>
Acc=[select id,otherphone from Account where id in :ids];
List<Contact> c=[select
id,otherphone from contact where Accountid IN : Acc];
Map<id,Account>
ContactMaps=new Map<Id,Account>();
List<contact>Updatecontact=new
List<Contact>();
for(Account:Acc)
{
ContactMaps.put(Acc.id,Acc);
}
for(Contact con:c)
{
Con.OtherPhone=contactMaps.get(con.Accountid).phone;
Updatecontact.add(Con);
}
Update Updatecontact;
|
No comments:
Post a Comment