检查存在或捕获异常?

时间:2012-08-28 06:25:44

标签: salesforce apex-code soql

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

最好的方法是什么?

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

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

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分:1)

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

答案 2 :(得分: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'); 
}
相关问题