function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Harish1234Harish1234 

savepoint and rollback?

hi,
Will any one helps me to give sample code with description where we wnat to go for savepoint and rollback with an real time example ..
Best Answer chosen by Harish1234
Harish1234Harish1234
hi
Ankit Arora,
               
                   Please explain me clearly with an real time example where we can use savepoint and rollback?

All Answers

Ankit AroraAnkit Arora
Suppose, There is a scenario where you insert parent with child record from visualforce page.

Case 1 : Unfortunately there was any error in creating child record(like user didn't fill required fields), but parent has been created successfully.

case 2 : User has filled the required information and clicked on save button again. So in this case there will be two parents created.

Now if you look into data base, there will be two parent records (from case one with no child and from case 2 with a child).
So case one could be avoided by using savepoint and rollback.

The syntax is to set the save point before any dml and then rollback to that savepoint when you face any error.


Savepoint sp = Database.setSavepoint();
try{
    insert parent;
    insert child;
}
catch(exception ex){
    Database.rollback(sp);
}

Another explaination :

Savepoint and roll back will help us to create your own transcation. Suppose you  have written long code which contains many more DML statement, at the some point you will want this DML statement should not be executed, you may need to modify your code, at that time you will have to return that point, savepoint will identifies that point , Rollback will  restore the database to that point(savepoint).
Here is some code you can refer

Account a = new Account(Name = 'xxx'); insert a;
   System.assertEquals(null, [SELECT AccountNumber FROM Account WHERE Id = :a.Id].
                              AccountNumber);

   // Create a savepoint while AccountNumber is null
   Savepoint sp = Database.setSavepoint();

   // Change the account number
   a.AccountNumber = '123';
   update a;
   System.assertEquals('123', [SELECT AccountNumber FROM Account WHERE Id = :a.Id].
                                AccountNumber);

   // Rollback to the previous null value
   Database.rollback(sp);
   System.assertEquals(null, [SELECT AccountNumber FROM Account WHERE Id = :a.Id].
                               AccountNumber);

I picked these from this post : https://developer.salesforce.com/forums?id=906F000000092kUIAQ

Would recommend you to search in boards as many of the questions are already in here :)
Harish1234Harish1234
hi
Ankit Arora,
               
                   Please explain me clearly with an real time example where we can use savepoint and rollback?
This was selected as the best answer