删除触发器出错

时间:2017-06-28 22:15:01

标签: sql-server tsql database-trigger

此触发器应从父表中删除未从子表中删除的行。错误如下图所示。

我的代码尝试:

CREATE TRIGGER ProductDeleted ON Product 
for DELETE AS 
BEGIN 
     DELETE FROM OrderItem
     WHERE ProductID = (SELECT ProductID FROM DELETED)
END
请帮助我

enter image description here

2 个答案:

答案 0 :(得分:2)

您可以通过在外键约束(例如

)上添加CASCADE DELETE提示来简化它
 CREATE TABLE OrderItem
    (
     ID INT ,
     ProductID NOT NULL UNIQUE
        CONSTRAINT fk_Products 
           REFERENCES Products (ID) ON DELETE CASCADE
    );

由于您已有表,因此您只需删除约束并重新创建一个新表。

ALTER TABLE OrderItem DROP
   CONSTRAINT fk_ProductID;

ALTER TABLE OrderItem ADD
   CONSTRAINT fk_ProductID
      FOREIGN KEY (ID)
      REFERENCES Product (ID)
      ON DELETE CASCADE;

这意味着,无论何时从父表(Product)中删除记录,来自(OrderItem)的子记录也将被删除,因此您不必使用触发器,除非您想要这样做一些录音。

如果你真的坚持使用触发器,那么你可以稍微调整它:

ALTER TRIGGER ProductDeleted  on Product
INSTEAD OF DELETE AS
BEGIN
SET NOCOUNT ON;

/* First we are deleting referenced columns in OrderItem table */
DELETE FROM OrderItem 
where ProductID  IN (select deleted.ID /* Columns from product Table */ from deleted)

/* Now we are doing actual delete statement */
DELETE FROM Products where ID IN (select deleted.ID from deleted)
END

但是再一次你应该考虑使用ON CASCADE DELETE,它更容易设置,更容易维护,每个表只能有一个INSTEAD OF触发器,所以如果你需要做一些更有意义的事情你就必须改变这个,并增加额外的开销。

答案 1 :(得分:0)

添加SET NOCOUNT ON作为触发器正文中的第一件事(BEGIN之后)。