创建比较SQL Server中日期的触发器

时间:2017-04-18 17:59:55

标签: sql-server triggers

我对触发器很新,我似乎无法绕过它们。我们假设我有两张表:

CREATE TABLE Project 
(
    id INT NOT NULL IDENTITY(1, 1),
    startDate DATETIME,
    endDate DATETIME
);

CREATE TABLE Work 
(
    date DATETIME,
    projectId INT
);

我插入一些数据:

INSERT INTO Project VALUES ('2017-04-18', '2017-05-01'); /*id = 1*/
INSERT INTO Work VALUES ('2017-04-17', 1);

假设只有1个id = 1项目,这应该会顺利进行。但是,我的工作在项目开始前一天(不是在这种情况下)开始并没有多大意义。我如何创建一个基本上表示date cannot be < startDate OR > endDate的触发器?

2 个答案:

答案 0 :(得分:2)

这样的事情应该有效:

CREATE TRIGGER t_CheckInterval ON dbo.Work
   AFTER UPDATE, INSERT
AS 

IF NOT EXISTS (
    --if no records are returned then work date lies outside the project
    -- (start, end) interval
    SELECT 1
    FROM inserted AS i
    JOIN Project AS p 
       ON p.Id = i.projectId AND i.[date] BETWEEN p.startDate AND p.endDate 
)
BEGIN
    RAISERROR ('Error: Your error message here.', 16, 1)
    ROLLBACK TRANSACTION
END

GO

答案 1 :(得分:1)

在你的情况下,我建议使用CHECK CONSTRAINT,而不是使用触发器进行这类检查:

CREATE FUNCTION dbo.ufn_CheckWorkDate
(
    @WorkDate DateTime,
    @ProjectID INT
)
RETURNS BIT
AS
BEGIN
    DECLARE @Result BIT

    IF EXISTS (SELECT * FROM Project WHERE id = @ProjectID AND @WorkDate BETWEEN startdate AND endDate)
        SET @Result = 1
    ELSE
        SET @Result = 0

    RETURN @Result
END

GO

ALTER TABLE Work 
    WITH CHECK ADD CONSTRAINT CK_CheckWorkDate
    CHECK (dbo.ufn_CheckWorkDate(date, projectid) = 1)