2

如果记录存在,我想更新记录,如果不存在,我想插入新记录。

最好的方法是什么?

做一个Select Count()如果返回零然后插入,如果一个则查询记录,修改和更新,或者我应该尝试查询记录并捕获任何system.queryexception?

这一切都在 Apex 中完成,而不是来自 REST 或 JS API。

4

3 回答 3

3

添加到这里已经说过的内容,您希望在这些情况下使用 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;
于 2012-08-28T20:43:40.747 回答
1

如果可能的话,您应该使用upsert调用,一旦您进入并发调用领域,选择然后插入/更新方法就会出现问题,除非您遇到了将父行正确锁定为 select 调用的一部分的麻烦。

于 2012-08-28T16:08:34.357 回答
0

我会尝试使用列表和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'); 
}
于 2012-08-28T06:48:24.103 回答