Find your content:

Search form

You are here

Get ID with upsert

 
Share

I'm trying to insert/update a custom object in database with upsert but after the upsert I need to get the database ID.

Is there a way to get the new/updated ID on database without querying the database ?

I tried something like this without success :

Id id = upsert(myCustomObject);

Attribution to: SF_user

Possible Suggestion/Solution #1

Salesforce sets these IDs back to list that is being upserts.

For example

Upsert xxx;

now after this line you can put a loop to display ids like below -

for(TypeXXX afterUpsert : xxx){
   system.debug('*** Id = ' + afterUpsert.id);
}

Attribution to: Pramod Kumar

Possible Suggestion/Solution #2

Although the answer is the easiest solution, another way is to use Database.upsert(List) call. From there, you can iterate through the array of Database.UpsertResult's returned. More info here: https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_database.htm#apex_System_Database_upsert_2

Here's a small example of the Database.upsert call:

Set<Id> myIds = new Set<Id>();
for(Database.UpsertResult ur : Database.upsert(myRecords,false)){
    if(ur.isSuccess()){
        myIds.add(ur.getId());
    }
}

Attribution to: James Loghry
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/32754

My Block Status

My Block Content