[英]Compare inserted date with existing in trigger
I need to create trigger which will check if there is a value in the table with the same time and the same theater id 我需要创建触发器,该触发器将检查表中是否存在具有相同时间和相同剧院ID的值
CREATE TRIGGER trCheckSameTime
ON dbo.Poster
FOR INSERT,UPDATE
AS
IF EXISTS(SELECT P.Id_Poster
FROM Poster P, inserted I
WHERE P.Date = I.Date AND P.Id_Theater = I.Id_Theater)
BEGIN
ROLLBACK TRANSACTION
RAISERROR('There can''t be two spectacles at the same time in the same theater', 16, 10)
END
I'm trying to use this, so I want it when I enter 我正在尝试使用此功能,因此输入时需要
INSERT INTO Poster
VALUES (1,4,1,'20190420 16:00:00')
INSERT INTO Poster
VALUES (1,4,1,'20190420 16:00:00')
To trigger forbid it to do, but this trigger prohibits entering any data in the table. 要触发它禁止这样做,但是此触发器禁止在表中输入任何数据。
3rd Value in table is theater_id and 4rth is date, 表中的第3个值是theater_id,第4个是日期,
You need to check before the data inserted as 您需要检查之前插入的数据为
CREATE TRIGGER trCheckSameTime
ON dbo.Poster
INSTEAD OF INSERT, UPDATE
AS
IF NOT EXISTS(
SELECT 1
FROM dbo.Poster P INNER JOIN INSERTED I
ON P.Id_Theater = I.Id_Theater
AND
P.[Date] = I.[Date]
)
BEGIN
INSERT INTO dbo.Poster(<Columns Here>)
SELECT <Columns Here> FROM INSERTED;
END
ELSE
BEGIN
RAISERROR('There can''t be two spectacles at the same time in the same theater', 16, 10)
END
You can also create a constraint
which is the better solution for your issue. 您还可以创建
constraint
,这是针对您的问题的更好解决方案。
ALTER TABLE dbo.Poster
ADD CONSTRAINT <Constraint Name Here> UNIQUE(Id_Theater, [Date]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.