Delete data with foreign key in SQL Server table

后端 未结 9 622
青春惊慌失措
青春惊慌失措 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:07

    You need to manually delete the children. the <condition> is the same for both queries.

    DELETE FROM child
    FROM cTable AS child
    INNER JOIN table AS parent ON child.ParentId = parent.ParentId
    WHERE <condition>;
    
    DELETE FROM parent
    FROM table AS parent
    WHERE <condition>;
    
    0 讨论(0)
  • 2020-12-12 21:08

    So, you need to DELETE related rows from conflicted tables or more logical to UPDATE their FOREIGN KEY column to reference other PRIMARY KEY's from the parent table.

    Also, you may want to read this article Don’t Delete – Just Don’t

    0 讨论(0)
  • 2020-12-12 21:08

    Set the FOREIGN_KEY_CHECKS before and after your delete SQL statements.

    SET FOREIGN_KEY_CHECKS = 0;
    DELETE FROM table WHERE ...
    DELETE FROM table WHERE ...
    DELETE FROM table WHERE ...
    SET FOREIGN_KEY_CHECKS = 1;
    

    Source: https://alvinalexander.com/blog/post/mysql/drop-mysql-tables-in-any-order-foreign-keys.

    0 讨论(0)
  • 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".

    0 讨论(0)
  • 2020-12-12 21:14

    To delete data from the tables having relationship of parent_child, First you have to delete the data from the child table by mentioning join then simply delete the data from the parent table, example is given below:

    DELETE ChildTable
    FROM ChildTable inner join ChildTable on PParentTable.ID=ChildTable.ParentTableID
    WHERE <WHERE CONDITION> 
    
    
    DELETE  ParentTable
    WHERE <WHERE CONDITION>
    
    0 讨论(0)
  • 2020-12-12 21:29

    You can disable and re-enable the foreign key constraints before and after deleting:

    alter table MyOtherTable nocheck constraint all
    delete from MyTable
    alter table MyOtherTable check constraint all
    
    0 讨论(0)
提交回复
热议问题