0

I have two tables in the database and I would like to delete on cascade with a trigger. I use to use a cascade deleting in the relationship, but in this case I have more tables and SQL Server does not let me to set cascde deleting in the relationship because it would create a cycle.

So I want to create a trigger to delete the registers of the table that I can't set cascade deleting in the relationship.

I use this trigger:

CREATE TRIGGER trg_myTrigger
   ON  Componentes
   AFTER DELETE
AS 
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for trigger here
    Delete from mytable2 where IDParentFromTable1 IN(select deleted.IDtable1 from deleted)
END
GO

However I get and error of foreign key.

really I don't know why I get this error.

Thanks.

4

1 回答 1

2

The trigger fires after the DELETE, so the foreign key error happens before the trigger runs.

You need to use one of

  • A stored proceure to delete mytable2 then Componentes
  • An INSTEAD OF (before trigger)
  • Two separate deletes in a transaction
于 2013-05-15T09:27:07.727 回答