global class AccountSetOwnerBatch implements Database.Batchable { String query; global AccountSetOwnerBatch() { } global Database.QueryLocator start(Database.BatchableContext BC) { String[] departmentTypes = new String[] {'戦略科室分類 その他', '戦略科室分類 呼吸科', '戦略科室分類 婦人科', '戦略科室分類 普外科', '戦略科室分類 泌尿科', '戦略科室分類 消化科', '戦略科室分類 耳鼻喉科','戦略科室分類ET'}; //战略科室类型 List rects = [select Id, Name from RecordType where IsActive = true and SobjectType = 'Account' and Name IN :departmentTypes]; List deptRectIds = new List(); for (RecordType rect : rects) { deptRectIds.add(rect.Id); } //战略科室 return Database.getQueryLocator([select id,OwnerId,ParentId from Account where RecordTypeId in :deptRectIds and Owner.IsActive = true and Is_Active__c <> '無効']); } global void execute(Database.BatchableContext BC, List scope) { //战略科室id List accIdlist = new List(); List accZDeptList = new List(); //战略科室 accZDeptList = scope; Map accZDeptMap = new Map(); for(Account accZDept :accZDeptList){ if(!accZDeptMap.containskey(accZDept.id)){ accIdlist.add(accZDept.id); } accZDeptMap.put(accZDept.id, accZDept); } //科室 List updateDeptList = new List(); List accDeptList = [select id,OwnerId,ParentId from Account where ParentId in :accIdlist and Is_Active__c <> '無効']; for(Account accDept : accDeptList){ //科室对应的战略科室 Account accZDepts = accZDeptMap.get(accDept.ParentId); if(accZDepts != null && accDept.OwnerId != accZDepts.OwnerId){ accDept.OwnerId = accZDepts.OwnerId; updateDeptList.add(accDept); } } if(updateDeptList.size() >0){ update updateDeptList; } //客户人员 List updateConList = new List(); List ConList = [select id, Name, OwnerId, Strategic_dept_Class__c from Contact where Strategic_dept_Class__c in :accIdlist and Isactive__c <> '無効']; for(Contact Con : ConList){ //客户人员对应的战略科室 Account accZDeptc = accZDeptMap.get(Con.Strategic_dept_Class__c); if(accZDeptc != null && Con.OwnerId != accZDeptc.OwnerId){ Con.OwnerId = accZDeptc.OwnerId; updateConList.add(Con); } } if(updateConList.size() > 0){ update updateConList; } } global void finish(Database.BatchableContext BC) { // } }