declare @ownerId int = ; declare @ownerType varchar(3) = ; declare @userId int = ; with openRequests as ( select requestId, requestKey, toUserId, fromUserId, fromEmail, requestURL, handlerTemplatePath, requestTime, disposition, config, requestTitle, requestSubject, response, responseTime, requestTrackingCode, responseDueDate, requestAnnotation, requestSent, sendCount, case when toUserId = @userId then 'IN' else 'OUT' end as direction, cast( case when ownerId = @ownerId and ownerType = @ownerType then 1 else 0 end as bit ) as homeRequest from tbl_WRK_UserRequests with (nolock) where disposition = '?' and ownerId = @ownerId and ownerType = @ownerType and ( fromUserId = @userId or toUserId = @userId ) ), openRequestsFormatted as ( select r.*, f.firstName + ' ' + f.lastName as fromFullName, t.firstName + ' ' + t.lastName as toFullName from openRequests r left outer join tbl_Fspro_Members f with (nolock) on f.fspro_userId = r.fromUserId left outer join tbl_Fspro_Members t with (nolock) on t.fspro_userId = r.toUserId ), result as ( select * from openRequestsFormatted ) #forJSON( 'result', attributes.datastore, 'requestTime' )#