declare @ownerId int = ; declare @ownerType varchar(3) = ; declare @opportunityId int = ; declare @partnerId int; declare @partnerType varchar(3); declare @saleSubjectId int; declare @saleSubjectType varchar(3); select @partnerId = partnerId, @partnerType = partnerType, @saleSubjectId = case when skuId is not null then skuId else prodId end, @saleSubjectType = case when skuId is not null then 'SKU' else 'PRD' end from tbl_DW_Opportunities_#attributes.ownerType##attributes.ownerId# where ownerId = @ownerId and ownertype = @ownerType and opportunityId = @opportunityId; select top 1 i.dispositionDate, i.interactionDate, i.partnerId, i.partnerType, i.disposition, i.interactionId, case when i.disposition = '?' then 1 else 0 end as editable, case when i.disposition = '?' then 1 else 2 end statusSort from tbl_CRM_Interactions i with (nolock) inner join tbl_CRM_InteractionSaleDetails isd with (nolock) on isd.interactionId = i.interactionId and isd.ownerId = i.ownerId and isd.ownerType =i.ownerType where i.ownerId = @ownerId and i.ownerType = @ownerType and i.partnerType = @partnerType and i.partnerId = @partnerId and isd.saleSubjectId = @saleSubjectId and isd.saleSubjectType = @saleSubjectType order by statusSort, i.interactionDate desc, i.interactionId desc for json auto, include_null_values