How to delete rows in tables that contain foreign keys to other tables

前端 未结 5 1380
借酒劲吻你
借酒劲吻你 2020-12-05 00:07

Suppose there is a main table containing a primary key and there is another table which contains a foreign key to this main table. So if we delete the row of main table it w

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-05 00:33

    If you have multiply rows to delete and you don't want to alter the structure of your tables you can use cursor. 1-You first need to select rows to delete(in a cursor) 2-Then for each row in the cursor you delete the referencing rows and after that delete the row him self.

    Ex:

    --id is primary key of MainTable
        declare @id int
        set @id = 1
        declare theMain cursor for select FK from MainTable where MainID = @id
        declare @fk_Id int
        open theMain
        fetch next from theMain into @fk_Id
        while @@fetch_status=0
        begin
            --fkid is the foreign key 
            --Must delete from Main Table first then child.
            delete from MainTable where fkid = @fk_Id
            delete from ReferencingTable where fkid = @fk_Id
            fetch next from theMain into @fk_Id
        end
        close theMain
        deallocate theMain
    

    hope is useful

提交回复
热议问题