I have a table with datetime and want to check if there is some entry with datetime in +-30 minutes period relative to inserted value. So i write this constraint:
USE [Test]
GO
/****** Object: UserDefinedFunction [dbo].[CanInsertReception] Script Date: 23.09.2015 12:19:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[CanInsertReception] (@receptionBegin datetime)
RETURNS bit
AS
BEGIN
DECLARE @result bit;
IF EXISTS(SELECT * FROM Main
where DATEDIFF(MINUTE, ReceptionBegin, @receptionBegin) <= 30 or DATEDIFF(MINUTE, @receptionBegin, ReceptionBegin) <= 30)
SET @result = 0
ELSE
SET @result = 1
return @result;
END;
GO;
ALTER TABLE Main
ADD CONSTRAINT CheckIfCanInsertReception
CHECK (dbo.CanInsertReception(ReceptionBegin) = 1);
but when I try to insert any data this check do not allow to insert it, But when I execute this script, which is doing the same:
DECLARE @receptionBegin datetime = '2015-01-01 09:00:00'
DECLARE @result bit;
IF EXISTS(SELECT * FROM Main
where DATEDIFF(MINUTE, ReceptionBegin, @receptionBegin) <= 30 or DATEDIFF(MINUTE, @receptionBegin, ReceptionBegin) <= 30)
SET @result = 0
ELSE
SET @result = 1
SELECT @result
I get expected output 1
What am I doing wrong here?