select top 1 batchId, batchTime from tbl_EAI_InboundBatches with (nolock) where ownerId = and ownerType = and fileFormat = '$NXT_STAFF_EXPORT_CSV' and batchTime < and status = 'OK' order by batchTime desc drop table if exists [#_tempTable#]; with export as ( SELECT distinct f.FSPro_UserID rep_id, FirstName + ' ' + LastName as Name, f.title, tm.teamMemberRole, f.LastLoginDate, f.FirstName first_name, f.LastName last_name, f.email, f.CellPhone cell_phone, ter.territoryid territory_id, f.loginEnabled login_enabled, ter.name as territory_access, t.territoryId as primary_territory_id, t.name as primary_territory, f.primaryOfficeId, f.officeAddrSame, rtrim( case when f.officeAddrSame = 0 then bo.broker_postal_address else f.address1 end ) address_1, rtrim( case when f.officeAddrSame = 0 then bo.broker_postal_address2 else f.address2 end ) address_2, rtrim( case when f.officeAddrSame = 0 then bo.broker_postal_city else f.city end ) city, rtrim( case when f.officeAddrSame = 0 then bo.broker_postal_state else f.State end ) state, rtrim( case when f.officeAddrSame = 0 then bo.broker_postal_zip else f.ZipCode end ) zip FROM tbl_FSPro_Members f with (nolock) inner join tbl_TER_Territories t with (nolock) on f.PrimaryTerritoryID = t.territoryId left outer join tbl_ter_teammembers tm on tm.teammemberuserid = f.FSPro_UserID and tm.ownerid = f.ownerId and tm.ownertype = f.FSL_TableCode left outer join tbl_ter_territories ter on ter.territoryid = tm.territoryid left outer join tblBrokerOffices bo with (nolock) on bo.Broker_Office_ID = f.PrimaryOfficeID WHERE f.OwnerID = AND f.FSL_TableCode = AND staffmember = 1 and loginEnabled = 1 and ter.fmterritoryId > 0 and ter.parentTerritoryId > 0 ) select rep_id,first_name, last_name, title,login_enabled,address_1,address_2,city,state,zip,territory_access, territory_id,email,cell_phone, primary_territory_id, primary_territory into [#_tempTable#] from export
Exported #lsnumberformat( _exportCount )# Contacts
update tbl_EAI_inboundBatches set fileName = , ttlDays = 365 where batchId = and ownerId = and ownerType =