SELECT
case when bsr.fspro_userid is not null then bsr.firstName
else case when rm.fspro_userid is not null then rm.firstName
else pm.firstName
end
end cmFirstName,
case when bsr.fspro_userid is not null then bsr.lastName
else case when rm.fspro_userid is not null then rm.lastName
else pm.lastName
end
end cmLastName,
case when bsr.fspro_userid is not null then bsr.email
else case when rm.fspro_userid is not null then rm.email
else pm.email
end
end cmEmail,
coalesce( bsr.fspro_userid, coalesce( rm.fspro_userid, pm.fspro_userid )) cmUserId
FROM tbl_CDR_Distributors cdr
INNER JOIN tbl_TER_Territories t
ON t.territoryid = cdr.cdr_territoryid
AND t.ownerid = cdr.ownerid
AND t.fsl_tablecode = cdr.fsl_tablecode
left outer join tbl_FSPro_Members pm
on pm.fspro_userId = t.primaryManager
and pm.ownerId = t.ownerId
and pm.fsl_tablecode = t.fsl_tablecode
left outer join tbl_FSpro_Members bsr
on bsr.fspro_userid = cdr.mfr_bsr_id
left outer join tbl_SMA_BrokerOfficeLink sma
on sma.territoryId = t.territoryId
and sma.primaryOffice = 'Y'
left outer join tbl_SEC_MemGrpLink rml
on rml.partnerId = t.ownerId
and rml.partnerTyp = t.fsl_tablecode
and rml.brokerOfficeId = sma.brokerOfficeID
and rml.groupId =
left outer join tbl_FSpro_Members rm
on rm.fspro_userid = rml.fspro_userId
WHERE cdr.fsl_tablecode =
AND cdr.ownerid =
and cdr.cdr_recordId =
#htmleditformat( qmd_dispCDRDistrProfile.cdr_dstAddress1 )#unknown street, #htmleditformat( qmd_dispCDRDistrProfile.cdr_dstcity)#unknown city, #qmd_dispCDRDistrProfile.cdr_dststate#unknown state