declare @ownerId int = ; declare @ownerType varchar(3) = ; with subGroupsRaw as ( select distinct cho.cho_id, cho.cho_name, cho.cho_type from tbl_OPR_ClientOperators opr with (nolock) inner join tbl_OPR_SubGroups sg with (nolock) on sg.operatorId = opr.operatorId and sg.ownerId = opr.ownerId and sg.ownerType = opr.fsltablecode inner join tbl_CHO_Operators cho with (nolock) on cho.cho_id = opr.fsl_choId where opr.ownerID = @ownerId and opr.fsltablecode = @ownerType order by cho.cho_name ), subGroups as ( select cho_id as operatorId, cho_name as companyName, cho_type as subgroupType from subGroupsRaw with (nolock) ) #forJSON( 'subGroups', attributes.dataStore, 'companyName' )#