简体   繁体   English

比较插入的日期与触发器中现有的日期

[英]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.

相关问题 如何使用触发器将插入的值与现有值进行比较和更新? - How to compare and update an inserted value to existing value using a trigger? MySQL 触发器 - 复制新。 插入的数据与现有列值进行比较,如果匹配,则将它们插入其他表 - MySQL Trigger - Copy NEW. inserted data compare to existing column values and then insert them to other table if they match 触发比较插入到删除的数据问题 - Trigger compare inserted to deleted data issue 在Oracle SQL上将日期与触发器进行比较 - Compare Date with Trigger on Oracle SQL 触发以将插入表中的一行与插入前的表进行比较 - Trigger to compare a line from inserted table with a table before insertion 比较 mysql 触发器中两个表之间的新插入值 - compare new inserted value between two table in mysql trigger SQL触发器-想要比较现有的行值和要插入的值 - sql triggers - want to compare existing row value with value being inserted 如何将文本框中插入的日期与MYSQL数据库中的日期进行比较 - How to compare date inserted from textbox with date from MYSQL db 触发器根据其他表插入写入最后插入日期 - Trigger to write last inserted date based on other table inserts 将日期截断为一周并与现有变量进行比较 - truncate date to week and compare against existing variable
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM