我想知道电子邮件域是否存在于数据库中。例如:如果要插入xxx@abc.com,我想查看已存在或不存在相同域(abc.com)的电子邮件。以下是检查整个电子邮件的代码。
trigger trig_Contact_webToContact on Contact (before insert)
{
final String errMsg = 'The email already exists on another Contact: ';
Set< String > emailSet = new Set< String >();
for( Contact c : Trigger.new ) emailSet.add( c.Email );
Map< String, Id > duplicateContactMap = new Map< String, Id >();
for( Contact c : [select Id, Email from Contact where Email = :emailSet] )
duplicateContactMap.put( c.Email, c.Id );
for( Contact c : Trigger.new ){
Id duplicateContactId = duplicateContactMap.get( c.Email );
if( duplicateContactId != null )
c.addError( errMsg + duplicateContactId );
}
}
答案 0 :(得分:0)
首先,只从电子邮件获取域名,但不是整个电子邮件:
Set< String > emailDomainSet = new Set< String >();
for( Contact c : Trigger.new ) {
if (String.isBlank(c.Email)) continue;
int indexOfAt = c.Email.indexOf('@');
if (indexOfAt > 0) emailDomainSet.add( c.Email.substring(indexOfAt) );
}
然后,在您的情况下,您需要使用query(queryString)方法。首先编写一个SOQL字符串
string queryString = 'select name from Contact where ';
string whereClause = ' ';
for (string domainItem : emailDomainSet) {
whereClause += ' or Email like \'%'+domainItem + '\' ';
}
whereClause = whereClause.substring(4);//remove first or in where clause
queryString += whereClause;
然后,运行它。 而不是
for( Contact c : [select Id, Email from Contact where Email = :emailSet] )
你应该把
for( Contact c : (List<Contact>)Database.query(queryString) )