34 sql sql-server sql-server-2008
假设有一个包含主键的主表,另一个表包含该主表的外键.因此,如果我们删除主表的行,它也将删除子表.
我该如何写这个查询?
Lie*_*ers 22
从您的问题来看,我认为可以安全地假设您已启用CASCADING DELETES.
在这种情况下所需要的只是
DELETE FROM MainTable
WHERE PrimaryKey = ???
Run Code Online (Sandbox Code Playgroud)
您的数据库引擎将负责删除相应的引用记录.
one*_*hen 20
首先,作为一次性数据清理练习,删除孤立的行,例如
DELETE
FROM ReferencingTable
WHERE NOT EXISTS (
SELECT *
FROM MainTable AS T1
WHERE T1.pk_col_1 = ReferencingTable.pk_col_1
);
Run Code Online (Sandbox Code Playgroud)
其次,作为一次性模式更改练习,将ON DELETE CASCADE
引用操作添加到引用表上的外键,例如
ALTER TABLE ReferencingTable DROP
CONSTRAINT fk__ReferencingTable__MainTable;
ALTER TABLE ReferencingTable ADD
CONSTRAINT fk__ReferencingTable__MainTable
FOREIGN KEY (pk_col_1)
REFERENCES MainTable (pk_col_1)
ON DELETE CASCADE;
Run Code Online (Sandbox Code Playgroud)
然后,永久更新,引用表中的行将在删除其引用行时自动删除.
您可以使用delete cascade选项更改外键约束,如下所示.这将删除与主表行相关的chind表行.
ALTER TABLE MasterTable
ADD CONSTRAINT fk_xyz
FOREIGN KEY (xyz)
REFERENCES ChildTable (xyz) ON DELETE CASCADE
Run Code Online (Sandbox Code Playgroud)
小智 5
如果要删除多行并且不想更改表的结构,则可以使用游标。1-您首先需要选择要删除的行(在游标中) 2-然后对于游标中的每一行,您删除引用行,然后自己删除该行。
前任:
--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
Run Code Online (Sandbox Code Playgroud)
希望有用
归档时间: |
|
查看次数: |
181997 次 |
最近记录: |