我有一个带有日期时间的表,并想检查相对于插入值在 +-30 分钟内是否有一些带有日期时间的条目。所以我写了这个约束:
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);
但是当我尝试插入任何数据时,此检查不允许插入它,但是当我执行此脚本时,它的作用相同:
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
我得到预期的输出1
我在这里做错了什么?