Activity Forums Salesforce® Discussions What is Database.rollback in Salesforce?

  • Amarkant

    Member
    July 21, 2017 at 10:06 am

    Similar to the SQL rollback. Used to rollback the DML Transactions performed on the database in a single transaction sequence.

    For more details go through following link    Transaction control in Salesforce

  • Aman

    Member
    July 21, 2017 at 12:23 pm

    Hello Shariq,

    Before You Started With Database.rollback  you must knew about Database.savepoint .

    Database.savepoint :

    database.savepoint is a method which is used to define a point which can be roll back to. If any error occurs during a transaction, that contains many statements, the application will roll back to the most recent savepoint and the entire transaction will not be aborted. Any DML statement that occurs after the savepoint can be discarded, and the database can be restored to the same condition it was in at the time you generated the savepoint.

    you can refer to the following code:

    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);

  • Parul

    Member
    September 16, 2018 at 12:27 pm

    database.savepoint is a method which is used to define a point which can be roll back to. If any error occurs during a transaction, that contains many statements, the application will roll back to the most recent savepoint and the entire transaction will not be aborted.

    for example,

    Account acc = new Account();
    acc.name ='ABC';
    ----                      --------
    ----- some code ---------
    Savepoint sp = Database.setSavepoint();
    try{
    insert acc;
    }
    catch( Exception e ){
    Database.rollback( sp );
    }
    ------ the code continues -----

    In this exapmle, if any error occurs while inserting the acc then the entire transaction will rollbak to savepoint sp ( as specified in the catch section by Database.rollback method).

     

    Thanks

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos