这适用于MS SQL 2005服务器。我有一个查询删除表中的所有孤立记录。但是,此表具有自引用FK。我也需要删除这些,但目前还不清楚如何这样做。当前脚本删除所有未在其他表中显示为FK的记录,但我没有考虑自己的表中的自引用FK。表很简单:
PK, FK, DAta
1, NULL, jibberjab
2, 1, jibberjab2
3, 1, skdfasfa
答案 0 :(得分:2)
如果您要有多个级别,可以使用公用表表达式来获取需要删除的ID,并在一个语句中处理孤立及其所有后代:
WITH cte AS (
SELECT pk
FROM myTable
WHERE id = 1 --pk to delete
UNION ALL
SELECT t.pk
FROM myTable t
JOIN cte c
ON t.fk = c.pk
)
DELETE t
FROM cte c
JOIN myTable t
ON c.pk = t.pk
答案 1 :(得分:0)
最简单的方法是分两步完成,首先删除孤立的记录,然后删除第一次删除后现在孤立的引用子项:
DELETE FROM TABLE1
WHERE NOT EXISTS (SELECT 1 FROM TABLE2 WHERE TABLE2.FK = TABLE1.PK)
DELETE FROM TABLE1
WHERE NOT EXISTS (SELECT 1 FROM TABLE1 B WHERE B.FK = TABLE1.PK)
答案 2 :(得分:0)
您可以配置在父项删除时删除约束:
ALTER TABLE table1 WITH CHECK ADD CONSTRAINT FK_table1_table2 FOREIGN KEY(column1)
REFERENCES table2 (ID) ON DELETE SET NULL -- here
ALTER TABLE table1 CHECK CONSTRAINT FK_table1_table2
GO
答案 3 :(得分:0)
您正在尝试删除记录,同时保持自我参照完整性。我会建议
创建一个触发器(用于删除)
CREATE TRIGGER ON ExTable
FOR DELETE
AS
IF EXISTS (SELECT * FROM ExTable AS tbl
JOIN DELETED AS del ON del.FK=tbl1.PK)
DELETE FROM ExTable
FROM ExTable ex JOIN DELETED del ON
ex.FK=del.ID