Hello出于业余爱好的目的,我正在尝试使用MS SQL Server数据库创建一个C#应用程序,该数据库重新组合酒店系统。我现在正在尝试创建一个计算日期差异的SQL触发器。预订时间不得超过6周(42天)。但是,即使差价低于42天,即使差价为1天,我的触发功能也会发生。所以我不确定我做错了什么。
我的触发器:
create trigger trigger_reservation
on reservation
after update, insert
as
if exists
(
select reservationid, DATEDIFF(dd,Startdate,Enddate)
from reservation
group by reservationid, enddate, startdate
having DATEDIFF(dd,Startdate,Enddate) > 42
)
begin
raiserror('Error: Reservation may not be longer than 6 weeks',16, 1)
rollback transaction
end
答案 0 :(得分:3)
触发器的运行和维护成本很高。这种类型的检查可以通过简单的CHECK CONSTRAINT
CREATE TABLE reservation (
reservationid INT,
startdate DATE,
enddate DATE,
-- ...
CONSTRAINT reservation_dates_ck
CHECK(DATEDIFF(dd, startdate, enddate) < 43)
)
这是dbfiddle演示
以下是您使用触发器进行操作的方法
CREATE TRIGGER trigger_reservation
ON reservation AFTER UPDATE, INSERT
AS
IF EXISTS (
SELECT *
FROM inserted
WHERE DATEDIFF(dd, startdate, enddate) > 42
)
BEGIN
RAISERROR ('Error: Reservation may not be longer than 6 weeks', 16, 1);
ROLLBACK TRANSACTION;
RETURN
END;
这是dbfiddle演示