IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[AKUZ].[RESOURCE_QUOTA_LINK_Unique]'))
DROP TRIGGER [AKUZ].[RESOURCE_QUOTA_LINK_Unique]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [AKUZ].[RESOURCE_QUOTA_LINK_Unique]
   ON [AKUZ].[T_RESOURCE_QUOTA_LINK]
   AFTER INSERT, UPDATE
AS 
BEGIN
    
	if exists
	(
		select * 
		from [AKUZ].T_RESOURCE_QUOTA_LINK s1
		join [AKUZ].T_RESOURCE_QUOTA_LINK s2 on s1.[Resource] = s2.[Resource] and s1.ResourceQuotaLinkID <> s2.ResourceQuotaLinkID
			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] in (select distinct [Resource] from inserted)
	)
	begin
		raiserror('Конфликт расписаний',16,10)
	end

END
GO