drop function if exists akuz.RESOURCE_QUOTA_LINK_Unique_Check cascade;
CREATE FUNCTION akuz.RESOURCE_QUOTA_LINK_Unique_Check()
  RETURNS trigger
    AS
$BODY$
BEGIN
	if exists
	(
		select * 
		from AKUZ.T_RESOURCE_QUOTA_LINK s1
		inner join 
			AKUZ.T_RESOURCE_QUOTA_LINK s2 
			on s1.Resource = s2.Resource 
			and s1.ResourceScheduleID <> s2.ResourceScheduleID
			and 
			(
				((s1.DayType*((s1.WeekType&2)/2)) + (s1.DayType*((s1.WeekType&4)/4)*8)) 
				& 
				((s2.DayType*((s2.WeekType&2)/2)) + (s2.DayType*((s2.WeekType&4)/4)*8))
			) > 0
		where s1.Resource = new.Resource
	)
	then
		Raise Exception Using Message = 'Конфликт расписаний';
		return null;
	end if;
	Return New;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
--ALTER FUNCTION akuz.RESOURCE_QUOTA_LINK_Unique_Check() OWNER TO postgres;


CREATE TRIGGER RESOURCE_QUOTA_LINK_Unique
  AFTER INSERT OR UPDATE
  ON akuz.t_resource_quota_link
  FOR EACH ROW
  EXECUTE PROCEDURE akuz.RESOURCE_QUOTA_LINK_Unique_Check();