Select your Language

DML Operation Notes


        DML : (Data Manipulation Langugage
        -----------------------------------
        1. These are used to perform the changes on the data .
        2. We have following types of DML operation
            a. Insert
            b. Update
            c. Delete
            d. Undelete
            e. Merge
            f. Upsert
        3. If you are performing DML on the list of records then it is called bulk DML operation.
        4. They are two types of DML
            a. Atomic
            b. Non-Atomic
        5. Atomic Operation :
            a. Perform all or perform none.
            b. When we are performing DML on the list of records, if DML on any one of the record fails, the entire operation
               will fail,
            c. Any DML operation using the keywords insert, update, delete, undelete, merge, upsert is an atomic operation.
       
        6. Non-Atomic :
            a. When we are performing dml on group of records,if dml on any record fail,
               only that record will fail,rest of the operation will be success.
            b. If you want to perform dml as non-atomic we need to perform the dml
               using Database methods.
            c. Example :
                    Datebase.insert(sobject,flag)
                    Database.update(Sobject,flag)
       
        7. insert  :
            a. This is used to create a new record in the sobject.
            b. Syntax :
               insert sobject/Sobject[]
            c. Example :
                1. Create a new Account
                   Account acc =new Account();
                   acc.Name='Testing';
                   acc.Phone='1234';
                   acc.Industry='Banking';
                   insert acc;
                 Note : when we insert a new record ,all the validation rules ,
                        and workflow,triggers will run
       
                2. Create a contact record..
                    Contact con =new Contact();
                    con.LastName='Myla';
                    con.FirstName='Ankit';
                    con.Phone='12345';
                    con.Email='abc@xyz.com';
                    insert con;
       
                3. Create a opportunity record
                   Opportunity op =new Opportunity();
                   op.Name='Testing';
                   op.StageName='Closed Won';
                   op.CloseDate=System.today()+15;
                   op.Amount=10000;
                   insert op;
                4. Create a customer record (FirstName__c,LastName__c,Phone__c,Email__c)
                    Customer__c cust=new Customer__c();
                    cust.FirstName__c='Ankit';
                    cust.LastName__c='Myla';
                    cust.Phone__c='11111';
                    cust.Email__c='abc@xyz.com';
                    insert cust;
       
                5. Create a new Account with wilson as owner.
                    User u=[select id from User where firstName='wilson'];
                    Account acc =new Account();
                    acc.Name='Testing';
                    acc.Phone='050-1234';
                    acc.OwnerId=u.Id;
                    insert acc;
       
                6. Create a new Opportunity for the account whose name is Wipro
                    Account acc =[select id from Account where name='Wipro'];
                    Opportunity op =new Opportunity();
                    op.Name='Admin';
                    op.closeDate=System.now()+15;
                    op.Stage='Prospecting';
                    op.Amount=10000;
                    op.AccountId=acc.Id;
                    insert op;
       
                 7. Create a new Case for the Account whose name is Dell
                    Account acc =[select id from Account where name='Dell'];
                    Case c=new Case();
                    c.AccountId=acc.Id;
                    c.Priority='Normal';
                    c.status='Open';
                    c.Origing='Email';
                    c.Subject='Testing';
                    insert c;
                 8. Create a attachment for the account genepoint
                    a. Note: Attachment is a standard object
                             Fields : ParentId --> Id of the record for which attachment
                                                   should be created.
                                    : Body    --> Body of the attachment it is blob
                                   
                                    : Name    --> Name of the attachment
       
                        Account acc =[select id from Account where name='Genepoint'];
                        Blob body=Blob.valueOf('Ankit Myla');
                        Attachment files=new Attachment();
                        files.parentId=acc.Id;
                        files.body=body;
                        files.Name='Testing';
                        insert files;
                       
                    9. Create a attachment for Opportunity Salesforce Training
                        Document  d=[select id ,name,body from Document where name='Test'];
                        Opportunity op=[select id from Opportunity where name='Training'];
                        Attachment a=new Attachment();
                        a.Name=d.Name;
                        a.body=d.body;
                        a.ParentId=op.Id;
                        insert a;
       
                    10. Create a wilson as AccounTeamMember of Genpoint accout.
                         AccounTeamMember : When we want a group users to collabrate and work on a account ,then we create
                                            them as accountTeamMembers
       
                        Note : First Enable AccountTeams
                            Setup
                            |--->Build
                                 |---> Customize
                                       |---> Account
                                             |--->AccountTeams
                                                   |--->Enable
       
                        Note 2: Fields of AccountTeamMember
                                AccountId : Id of the account for which AccountTeamMember should be created
                                TeamMemberRole : Role of the teamMember
                                UserId : Id of the user ,whom you want to create  as teammember.
                                AccountAccessLevel : Type of access which you want to give to user on account
       
                                User u=[select id from User where firstName='Wilson'];
                                Account acc =[select id from Account where name='Genepoint'];
                                AccountTeamMember atm =new AccountTeamMember();
                                atm.AccountId=acc.Id;
                                atm.UserId=u.Id;
                                atm.TeamMemberRole='Account Manager';
                                atm.AccountAccessLevel='Edit';
                                insert atm;
       
                        11. Create a wilson as OpportunityTeamMember for Opportunity Training
                               
       
                        12. Create task for an account
                         
                            Task Fields :
                                1. OwnerId  :If of the user/Role to whom you want to assign the task
                                2. Subject  : It can be any string
                                3. WhatId   : Id of the record on which task is created
                                4. WhoId    : It is optional ,It is the id of the Lead or Contact who is associated with task
                                5.ActivityDate: Due Date for the task
                                6. Priority
                                7. Status
               
                            Account acc =[select id from Account where name='Genepoint'];
                            Task t =new Task();
                            t.subject='Schedule a call';
                            t.Priority='Normal';
                            t.status='Not started';
                            t.ActivityDate=System.today()+15;
                            t.whatId=acc.Id;
                            insert t;
           
                     13. Event  :
                         a. assignedto
                         b. startDateTime
                         c. EndDateTime
                         d. whoId
                         f. WhatId
                         g. ActivityDate
                         h.IsAllDayEvent
                         i. isPrivate
                         j. Phone
                         k. Email
       
       Usecases:
       ----------
       Event --->EventMembers
       Quote
       Order
       PriceBookEntry
       OpportunityLineItem
       QuoteLineItem
       Solution
       User
       Group
       GroupMember
       ChatterFeed
       ChatterComment
   
    8. Database.Error :
    1. Error is a pre-defined apex class.
    2. This is defined under the namespace of Database.
    3. This class contains the errors that are generated during DML operations
    a. getFields() :
       1. This method will return name of the fields on which error occured.
       2.Syntax : <!--  List<String> getFields() -->
   
        b. getMessage() :
       1. This method will return the error message that is generated during the dml
       2. Syntax : <!-- String getMessage()  -->
   
      9. Database.SaveResult :
    1. SaveResult is a pre-defined apex class .
    2. This class contains status of the dml (insert,update)operation that is performed on the object.
    3. Methods :
    a. isSuccess() :
       1. This will return the status of the DML operation.
       2. If the dml is success it will return true
       3. Failed return false .
       4. Syntax : Boolean isSuccess()
   
    b. getId() :
       1. This will return the Id of the record on which dml is performed
       2. Syntax : Id getId()
   
    c. getErrors() :
       1. This will return errors that are generated during the DML operation.
       2. Syntax : Database.Error[] getErrors()
   
    10. Database.insert(sobject[],falg):
    1. Insert is the method defined in the Database class
    2. If the flag is true, then DML operation of insert will run like atomic.
    3. If the flag is false ,then DML operation of insert will run as non-atomic
    4. Syntax : Database.SaveResult[] Database.insert(sobject[],flag)
    <!--
                List<Account> accounts =new List<Account>();
                Account a1 =new Account(Name='TCS',Phone='1234');
                Account a2 =new Account(Phone='12345');
                accounts.add(a1);
                accounts.add(a2);
                Database.SaveResult[] result =Database.insert(accounts,false);
                for(Database.SaveResult s: result){
                    if(s.isSuccess()){
                        System.debug('Record Inserted Successfully Id:'+s.getId());
                    }else{
                        for(Database.Error er: s.getErrors()){
                            System.debug('Fields :'+er.getFields());
                            System.debug('Message:'+er.getMessage());
                        }
                    }
                }
-->
    11.DmlOptions.AssignmentRuleHeader
       ----------------------------------
            1. AssignementRuleHeader is a pre-define apex class.
            2. This class is defined under DMLoptions
            3. This class contains two variables .
                a. assignmentRuleID : This will specify the id of the assignemntRule
                b.useDefaultRule    : This is a boolean value ,when set as true ,default assignment rule is applied.
           
                Example :
                AssignmentRule rule=[select id from AssignmentRule where name='CustomAssign'];
                Database.DMLOptions  op =new Database.DMLOptions();
                op.AssignmentRuleHeader.assignmentRuleId=rule.id;
   
    12.Database.insert(Sobject[],dmloptions) :
       ------------------------------------------
    a. whlie creating a lead /case if you want to apply any assignment rule then we use dml options
    Example :
                AssignmentRule rule=[select id from AssignmentRule where name='CustomAssign'];
                Database.DMLOptions  op =new Database.DMLOptions();
                op.AssignmentRuleHeader.assignmentRuleId=rule.id;
                Lead l=new Lead();
                l.LastName='K';
                l.FirstName='Sravan';
                l.company='Testing';
                l.industry='Banking';
                l.Phone='12345';
                Database.insert(l,op);
   
    13. Update :
    a. If you want to perform any changes on the data which is already save to the object ,then we use
       dml operation of update.
    b. If you want to perform update
    1. Fetch the data from the database by using soql
    2. Modify the data and update to database.
    c. Syntax : update sobject/Sobject[]
        : Database.SaveResult[] Database.update(Sobject[],falg)
   
    Example 1:
    1. Fetch all the accounts whose rating is Warm and update their rating as Hot
    <!--
List<Account> accounts =[select id ,rating from Account where rating='Warm'];
for(Account a :accounts){
a.Rating='Hot';
}
update accounts;
-->
    2. Fetch all the opportunities whose stagename is prospecting and udpate their stagname as
       closed won and closeDate as today
       <!--
List<Opportunity> optyList =[select id,StageName,CloseDate from Opportunity where stageName='Prospecting'];
for(Opportunity op:optyList){
op.stageName='Closed Won';
op.closeDate=System.today();
}
update optyList;
-->
   
    3. Fetch all the leads which are owned by Ankit and re-assign them Queue: HydTeam
    <!--
User u =[select id from User where firstName='Ankit'];
Group g =[select id from Group where type='Queue' and Name='HydTeam'];
List<Lead> leads =[select id ,ownerId from Lead where ownerId=:U.Id];
for(Lead l:leads){
l.ownerId=g.Id;
}
update leads;

Database.SaveResult[] result=Database.update(leads,false);

-->
   
    14. Delete :
    a. This will delete the  data from the database.
    b. Fetch the data from database and delete.
    c. Syntax : delete Sobject/Sobject[]
      : Database.DeleteResult[] Database.delete(Sobject[],false)
    d. Database.DeleteResult :
       1. DeleteResult is a pre-defined apex class.
       2. This will contain the status of the DML operation delete .
       3. Methods :
    a. isSuccess()
    b. getId()
        c. getErrors()
   
    Example :1
    a. Delete all the leads which are created in the last months.
    <!--
List<Lead> leads =[select id,FirstName from Lead where createdDate=Last_Month];
delete leads;
    -->
   
    b. Fetch all the accounts with corresponding contacts.
       If the account doesnt contain any contact then delete account.
       <!--
                        List<Account> accounts =[select id ,Name,(select id,lastname,firstname from Contacts) from Account];
                        List<Account> accs =new List<Account>();
                        for(Account a: accounts){
                            if(a.contacts.size()==0){
                                accs.add(a);
                            }
                        }
                        Database.DeleteResult[] result=Database.delete(accs,false);

No comments:

Post a Comment