Delete data with foreign key in SQL Server table

后端 未结 9 617
青春惊慌失措
青春惊慌失措 2020-12-12 20:32

I\'m going to delete data in an SQL Server table (parent) which has a relationship with another table (child).
I tried the basic Delete query. But it isn\'t working (and

9条回答
  •  一生所求
    2020-12-12 21:13

    here you are adding the foreign key for your "Child" table

    ALTER TABLE child
    ADD FOREIGN KEY (P_Id)
    REFERENCES parent(P_Id) 
    ON DELETE CASCADE
    ON UPDATE CASCADE;
    

    After that if you make a DELETE query on "Parent" table like this

    DELETE FROM parent WHERE .....
    

    since the child has a reference to parent with DELETE CASCADE, the "Child" rows also will be deleted! along with the "parent".

提交回复
热议问题