Foreign key constraint may cause cycles or multiple cascade paths?

后端 未结 9 1421
感情败类
感情败类 2020-11-21 23:07

I have a problem when I try to add constraints to my tables. I get the error:

Introducing FOREIGN KEY constraint \'FK74988DB24B3C886\' on table \'Empl

9条回答
  •  春和景丽
    2020-11-21 23:58

    Trigger is solution for this problem:

    IF OBJECT_ID('dbo.fktest2', 'U') IS NOT NULL
        drop table fktest2
    IF OBJECT_ID('dbo.fktest1', 'U') IS NOT NULL
        drop table fktest1
    IF EXISTS (SELECT name FROM sysobjects WHERE name = 'fkTest1Trigger' AND type = 'TR')
        DROP TRIGGER dbo.fkTest1Trigger
    go
    create table fktest1 (id int primary key, anQId int identity)
    go  
        create table fktest2 (id1 int, id2 int, anQId int identity,
            FOREIGN KEY (id1) REFERENCES fktest1 (id)
                ON DELETE CASCADE
                ON UPDATE CASCADE/*,    
            FOREIGN KEY (id2) REFERENCES fktest1 (id) this causes compile error so we have to use triggers
                ON DELETE CASCADE
                ON UPDATE CASCADE*/ 
                )
    go
    
    CREATE TRIGGER fkTest1Trigger
    ON fkTest1
    AFTER INSERT, UPDATE, DELETE
    AS
        if @@ROWCOUNT = 0
            return
        set nocount on
    
        -- This code is replacement for foreign key cascade (auto update of field in destination table when its referenced primary key in source table changes.
        -- Compiler complains only when you use multiple cascased. It throws this compile error:
        -- Rrigger Introducing FOREIGN KEY constraint on table may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, 
        -- or modify other FOREIGN KEY constraints.
        IF ((UPDATE (id) and exists(select 1 from fktest1 A join deleted B on B.anqid = A.anqid where B.id <> A.id)))
        begin       
            update fktest2 set id2 = i.id
                from deleted d
                join fktest2 on d.id = fktest2.id2
                join inserted i on i.anqid = d.anqid        
        end         
        if exists (select 1 from deleted)       
            DELETE one FROM fktest2 one LEFT JOIN fktest1 two ON two.id = one.id2 where two.id is null -- drop all from dest table which are not in source table
    GO
    
    insert into fktest1 (id) values (1)
    insert into fktest1 (id) values (2)
    insert into fktest1 (id) values (3)
    
    insert into fktest2 (id1, id2) values (1,1)
    insert into fktest2 (id1, id2) values (2,2)
    insert into fktest2 (id1, id2) values (1,3)
    
    select * from fktest1
    select * from fktest2
    
    update fktest1 set id=11 where id=1
    update fktest1 set id=22 where id=2
    update fktest1 set id=33 where id=3
    delete from fktest1 where id > 22
    
    select * from fktest1
    select * from fktest2
    

提交回复
热议问题