select loc.partnerId sourceOperatorId, opr.fsltablecode ownerType, opr.ownerId, opr.operatorId partnerId, 'OPR' partnerType, loc.latitude, loc.longitude, loc.geography, loc.source, loc.lastUpdated
from tbl_OPR_ClientOperators opr
inner join ( select distinct a1.objectId, a1.objectType, a1.ownerId, a1.alias, a1.ownerType from tbl_IMPORT_Aliases a1 where a1.ownerId = 122 and a1.ownerType = 'MFR' and a1.objectType = 'OPR' ) a
on a.objectId = opr.operatorId
and a.ownerId = opr.ownerId
and a.ownerType = opr.fsltablecode
and a.objectType = 'OPR'
inner join tbl_GEO_Locations loc
on loc.ownerId = 14
and loc.ownerType = 'BRO'
and loc.partnerType = 'OPR'
and loc.partnerId = right( a.alias, len( a.alias ) - 13 )
where opr.ownerId = 122
and a.alias like 'M:122;B:14;O:%'
and not exists ( select * from tbl_GEO_Locations geo where geo.partnerId = opr.operatorId and geo.partnerType = 'OPR' and geo.ownerId = opr.ownerId and geo.ownerType = opr.fsltablecode )
insert into tbl_GEO_Locations ( ownerType, ownerId, partnerId, partnerType, latitude, longitude, geography, source, lastUpdated )
select opr.fsltablecode ownerType, opr.ownerId, opr.operatorId partnerId, 'OPR' partnerType, loc.latitude, loc.longitude, loc.geography, loc.source, loc.lastUpdated
from tbl_OPR_ClientOperators opr
inner join ( select distinct a1.objectId, a1.objectType, a1.ownerId, a1.alias, a1.ownerType from tbl_IMPORT_Aliases a1 where a1.ownerId = 122 and a1.ownerType = 'MFR' and a1.objectType = 'OPR' ) a
on a.objectId = opr.operatorId
and a.ownerId = opr.ownerId
and a.ownerType = opr.fsltablecode
and a.objectType = 'OPR'
inner join tbl_GEO_Locations loc
on loc.ownerId = 14
and loc.ownerType = 'BRO'
and loc.partnerType = 'OPR'
and loc.partnerId = right( a.alias, len( a.alias ) - 13 )
where opr.ownerId = 122
and opr.operatorId =
and loc.partnerId =
and a.alias like 'M:122;B:14;O:%'
and not exists ( select * from tbl_GEO_Locations geo where geo.partnerId = opr.operatorId and geo.partnerType = 'OPR' and geo.ownerId = opr.ownerId and geo.ownerType = opr.fsltablecode )