触发以检查逻辑日期更新

时间:2014-03-22 15:51:06

标签: sql sql-server triggers

构建员工数据库,我们希望确保数据库无法正确更新,并且就业结束日期在开始日期之前。我们希望使用触发器来阻止更新,抛出错误和回滚。

我知道这是错的,但我就是这样:

CREATE TRIGGER EmpLeaveWarn on Employee FOR UPDATE 
AS
    IF(select End_Date < Start_Date)
    BEGIN
        RAISERROR ('The End date must come after the Start date')
        ROLLBACK TRAN
        RETURN
    END
GO

对于Microsoft SQL Server。

提前致谢。

2 个答案:

答案 0 :(得分:1)

不需要触发器,只需使用约束:

alter table EmpLeaveWarn
    add constraint check_end_date check (End_Date >= Start_Date);

答案 1 :(得分:0)

实现这一目标的最简单方法是使用检查约束,而不是触发器:

ALTER TABLE Employee ADD CONSTRAINT Employee_Date_Check CHECK ( End_Date >= Start_Date)