我一直在尝试使触发器工作。我的目的是进行触发器检查,以便在插入表时另一个表上是否存在值。 以下是不起作用的触发器:
CREATE TRIGGER trigger1
ON table1
AFTER INSERT
AS
declare @tId int
IF EXISTS ((Select @tId from inserted i join table2 on i.tId=table2.Id
join table3 on i.tId=table3.tId
where i.tId NOT IN (SELECT tId from table3)
and table2.ApplicationDate > '2018-01-31 00:00:00.0000000'
and table2.cnumber is NOT NULL))
BEGIN
ROLLBACK transaction
SET NOCOUNT ON;
END
GO
任何人都可以向我指出正确的方向。
答案 0 :(得分:-1)
您的问题尚不清楚。 这些部分组合起来毫无意义:
join table3 on i.tId=table3.tId
where i.tId NOT IN (SELECT tId from table3)
->没有匹配行!
检查两个表之间没有依赖性的简单解决方案:
CREATE TRIGGER trigger1
ON table1 AFTER INSERT
AS
BEGIN
IF (EXISTS (SELECT Id FROM table2 WHERE Id IN(SELECT tId FROM Inserted))
OR EXISTS (SELECT Id FROM table3 WHERE Id IN(SELECT tId FROM Inserted))) BEGIN
ROLLBACK;
END
END