我想更新記錄,如果記錄存在或插入一個新的,如果不存在。檢查存在或發現異常?
什麼是最好的方法?
做一個Select Count()
如果返回零然後插入,如果有人然後查詢記錄,修改和更新,或者我應該只是試圖查詢記錄和捕獲任何system.queryexception?
這一切都在Apex中完成,而不是從REST或JS API完成。
我想更新記錄,如果記錄存在或插入一個新的,如果不存在。檢查存在或發現異常?
什麼是最好的方法?
做一個Select Count()
如果返回零然後插入,如果有人然後查詢記錄,修改和更新,或者我應該只是試圖查詢記錄和捕獲任何system.queryexception?
這一切都在Apex中完成,而不是從REST或JS API完成。
加入已經在這裏說過的內容,您想在這些情況下使用FOR UPDATE來避免superfell指的是什麼。所以,
Account theAccount;
Account[] accounts = [SELECT Id FROM Account WHERE Name = 'TEST' LIMIT 1 FOR UPDATE];
if(accounts.size() == 1)
theAccount = accounts[0];
else
theAccount = new Account();
// Make modifications to theAccount, which is either:
// 1. A record-locked account that was selected OR
// 2. A new account that was just created with new Account()
upsert theAccount;
我會用一個列表和isEmpty()
功能試試吧:
List<Account> a = [select id from account where name = 'blaahhhh' Limit 1];
if(a.isEmpty()){
System.debug('#### do insert');
}
else{
System.debug('#### do update');
}
好主意。這種方法的任何理由? –
您應該使用upsert呼叫如果在所有可能的選擇,然後插入/更新的方法是有問題的,一旦你進入的同時境界除非你正確地鎖定父行作爲選擇呼叫的一部分。
upsert有什麼問題? –