DECLARE @startOfLastWeek DATE; DECLARE @endOfLastWeek DATE; SET @startOfLastWeek = DATEADD( WEEK, DATEDIFF( WEEK, 0, GETDATE() ) - 7, 0 ); SET @endOfLastWeek = DATEADD( DAY, 6, @startOfLastWeek ); select top 5 la.recordTableCd, la.recordDescrip, la.eventTime, cho.cho_id as pkId, cho.cho_type as companyType, cho.cho_name as companyName, cho.cho_address as address, cho.cho_city as city, cho.cho_state as state, cho.cho_zipcode as zipcode, seg.subSegment as segment, left( la.eventDetail, charIndex( ' ', la.eventDetail + ' ' ) - 1 ) as fieldUpdated, la.formFields, case when exists ( select 1 from tbl_TRK_LibraryActivity la_mrge with (nolock) where la_mrge.recordKey2 = la.recordKey1 and la_mrge.recordTableCd = la.recordTableCd and la_mrge.recordOwnerId = la.recordOwnerId and la_mrge.recordOwnerType = la.recordOwnerType and la_mrge.eventCd = 'MRGE' ) then 'Y' else 'N' end as dataMerged from tbl_TRK_LibraryActivity la with (nolock) inner join tbl_CHO_Operators cho with (nolock) on cho.cho_id = la.recordKey1 left outer join tbl_OPR_Segments seg on seg.segmentId = cho.cho_segmentId where la.recordOwnerId = 66 and la.recordOwnerType = 'MSC' and la.eventCd = 'UPD' and la.eventDetail in ( 'Name Changed', 'Type Changed', 'Address Changed', 'City Changed', 'State Changed', 'Zipcode Changed', 'Segment Changed' ) and la.eventTime >= @startOfLastWeek and la.eventTime < DATEADD( DAY, 1, @endOfLastWeek ) and exists ( select 1 from tbl_OPR_ClientOperators opr where opr.fsl_choId = cho.cho_id ) union select top 5 la.recordTableCd, la.recordDescrip, la.eventTime, dst.dstId as pkId, dst.dstCompanyType as companyType, dst.dstName as companyName, dst.dstAddr1 as address, dst.dstCity as city, dst.dstState as state, dst.dstZip as zipcode, '' as segment, left( la.eventDetail, charIndex( ' ', la.eventDetail + ' ' ) - 1 ) as fieldUpdated, la.formFields, case when exists ( select 1 from tbl_TRK_LibraryActivity la_mrge with (nolock) where la_mrge.recordKey2 = la.recordKey1 and la_mrge.recordTableCd = la.recordTableCd and la_mrge.recordOwnerId = la.recordOwnerId and la_mrge.recordOwnerType = la.recordOwnerType and la_mrge.eventCd = 'MRGE' ) then 'Y' else 'N' end as dataMerged from tbl_TRK_LibraryActivity la with (nolock) inner join tbl_DST_Distributors dst with (nolock) on la.recordKey1 = dst.dstId and la.recordTableCd = 'DSTR' where la.recordOwnerId = 66 and la.recordOwnerType = 'MSC' and la.eventCd = 'UPD' and la.eventDetail in ( 'Name Changed', 'Type Changed', 'Address Changed', 'City Changed', 'State Changed', 'Zipcode Changed' ) and la.eventTime >= @startOfLastWeek and la.eventTime < DATEADD( DAY, 1, @endOfLastWeek ) and exists ( select 1 from tbl_CDR_Distributors cdr where cdr.fsl_dstId = dst.dstId ) SELECT * from tbl_OPR_Segments with (nolock) WHERE segmentId = --->