-- ============================================= -- Author: -- Create date: -- Description: -- ============================================= CREATE FUNCTION [dbo].[fds__getCompanyContacts] ( @companyid bigint ) RETURNS TABLE AS RETURN ( WITH ps as ( SELECT [contactid] = p.[EntityId] from [mfr__*PartnerSet] as p WHERE p.property = 'Contact:Company' and p.[partnerId] = @companyid UNION SELECT [contactid] = p.[PartnerId] from [mfr__*PartnerSet] as p WHERE p.property = 'Company:Contacts' and p.[EntityId] = @companyid ) SELECT ct.* ,[isMainContact] = CAST( CASE WHEN cy.[MainContactId] is null then 0 WHEN cy.[MainContactId] = ct.[id] THEN 1 ELSE 0 END as bit) FROM [dbo].[mfr__contacts] as ct JOIN [dbo].[mfr__companies] as cy ON ct.[CompanyId] = cy.[id] WHERE ct.CompanyId = @companyid UNION SELECT ct.* ,[isMainContact] = CAST( CASE WHEN cy.[MainContactId] is null then 0 WHEN cy.[MainContactId] = ct.[id] THEN 1 ELSE 0 END as bit) FROM [dbo].[mfr__contacts] as ct JOIN ps ON ct.[id] = ps.[contactid] JOIN [dbo].[mfr__companies] as cy ON cy.[id] = @companyid )