String deletePrivelegeRoleSql = 'SELECT ROLEID__c, NAME__c, Id, PRIVELEGEID__r.ID, ROLEID__r.ID FROM PRIVILAGEROLE__c'; List<SObject> privelegeRoles = Database.query(deletePrivelegeRoleSql); if(privelegeRoles.size() > 0){//查询有记录的时候才对子表进行删除操作 PRIVILAGEROLE__c privelegeRole = (PRIVILAGEROLE__c)privelegeRoles[0]; ID privelegeId = privelegeRole.PRIVELEGEID__r.ID; ID roleId = privelegeRole.ROLEID__r.ID; try{ Database.delete(privelegeRole.Id); }catch(Exception e){ System.debug('error occured when deleting privelegerole!'); } try{ Database.delete(privelegeId); Database.delete(roleId); }catch(DmlException e){ System.debug('error occured when deleting privelege or role'); } }