CREATE OR REPLACE FUNCTION public.trg_company_iu_fn()
 RETURNS trigger
 LANGUAGE plpgsql
AS $function$   
declare
begin
	IF EXISTS(SELECT NULL FROM "Company" C where C."ADGuid" = new."ADGuid" AND C."Id" <> new."Id" ) THEN
		RAISE EXCEPTION 'The company with this unique identifier already exists. TRG_COMPANY_IU_SAMEGUID';
	END IF;

	IF (new."CustomerKey" IS NOT NULL and EXISTS(SELECT NULL FROM "Company" C where  C."CustomerKey" IS NOT NULL and  new."CustomerKey" = C."CustomerKey" AND C."Id" <> new."Id" )) THEN
		RAISE EXCEPTION 'IX_Company_CustomerKey';
	END IF;

	RETURN NEW;
END;
$function$
;
