declare @ownerId int = ; declare @ownerType varchar(3) = ; with brokers as ( select distinct b.broker_id, b.broker_name from tbl_SMA_BrokerOfficeLink sma with (nolock) inner join tblBrokers b with (nolock) on b.broker_id = sma.brokerId inner join tbl_TER_Territories t with (nolock) on t.territoryId = sma.territoryId and t.ownerId = sma.mfr_id and t.fsl_tablecode = 'MFR' where t.ownerId = @ownerId and t.fsl_tablecode = @ownerType and t.territoryId in ( ) ) #forJSON( 'brokers', attributes.datastore, 'broker_name' )#