1

我需要一个触发器来接收来自用户的数据(大约 1000 条记录的批量加载)并将它们存储在 Salesforce 数据库中。Trigger.new问题是用户可以在不同批次中甚至在不同批次中出现多次。自定义对象名称是CBK_User并且有一个EXTERNAL_ID(唯一的)称为USER_ID. 在我的代码中,我检查数据库中是否尚不存在用户:

Map<String, CBK_User__c> users = new Map<String,CBK_User__c> 
    ([select Id, USER_ID__c from CBK_User__c where USER_ID__c in : userIds]);

(userIds 具有 Trigger.new 对象的外部 id)

当我尝试插入时,它给了我错误:

DUPLICATE_VALUE, duplicate value found: USER_ID__c duplicates value on 
record with id: a1QJ0000000HRd8"

如何防止批量插入重复值?

4

1 回答 1

3

我已将您的问题改编为这个基本示例(练习 2:铅重复预防)

您应该首先从重复条目中清除“新”列表,然后从数据库中现有的列表中清除。

     trigger CBK_UserDuplicatePreventer on CBK_User__c (before insert, before update) {
        //Enter a map declaration to hold records which we will add,
        // this will become a unique map, no duplicate values within it.
        Map<String, CBK_User__c> cbkUserMap = new Map<String, CBK_User__c>();

        //The next few lines loop across the array of records that are passed into 
        //the trigger in bulk fashion from any API or User Interface database operation.
        //The goal of this loop is to ensure that there are no duplicates within 
        //the batch that we have received and to gather a list of externalIds that we will use later
        for (CBK_User__c cbkUser : System.Trigger.new) {

            /* Make sure we don't treat an externalId that
               isn't changing during an update as a duplicate. */
            if ((cbkUser.USER_ID__c != null) && (System.Trigger.isInsert ||
 (cbkUser.USER_ID__c != System.Trigger.oldMap.get(cbkUser.Id).USER_ID__c))) {

                // Make sure another new CBK_User__c isn't also a duplicate
                if (cbkUserMap.containsKey(cbkUser.USER_ID__c)) {
                    cbkUser.USER_ID__c.addError('Another new CBK_User__c has the same USER_ID.');
                } else {
                    cbkUserMap.put(cbkUser.USER_ID__c, cbkUser);
                }
            }
        }

        // Using a single database query, find all the CBK_User__c in
        // the database that have the same USER_ID as ANY
        // of the CBK_User__c being inserted or updated. */
        for (CBK_User__c cbkUser : [SELECT USER_ID__c FROM CBK_User__c WHERE USER_ID__c IN :cbkUserMap.KeySet()]) {
            CBK_User__c newCbkUser = cbkUserMap.get(cbkUser.USER_ID__c);
            newCbkUser.USER_ID__c.addError('A CBK_User__c with this USER_ID already exists.');
        }
    }
于 2012-06-26T23:30:20.437 回答