我有一个SQL Server,其中包含重复的行,而我想删除表tableObj
的特定列。我正在使用的查询是:
DELETE tableObj
WHERE id NOT IN
(SELECT MIN(id)
FROM tableObj
GROUP BY column_name);
此column_name
是重复的,我想删除包含同一列的所有其他行。现在,当我执行此查询时,出现以下错误:
The DELETE statement conflicted with the REFERENCE constraint "some_value". The conflict occurred in database "UH", table "Test.otherTable", column 'column_name'.
此otherTable
与tableObj
一一对应。现在,如何删除这些引用以及重复删除。
这是我找到重复项的方式:
SELECT column_name, COUNT(*)
FROM tableObj
GROUP BY column_name
HAVING
COUNT(*) > 1
给我的结果是:
column_name (no-specific column)
12345 2
23414 3
...........
...........
该映射将保留在映射表中,例如:
tableObjID otherTableId
执行DELETE
查询后,期望的结果是得到(COUNT = 1):
column_name (no-specific column)
12345 1
23414 1
...........
...........
答案 0 :(得分:0)
如果在otherTable
中启用了ON DELETE CASCADE
,则无需从Foreign Key constraint
中删除
否则,您首先需要从其他表中删除引用的数据,然后从表中删除主数据。
以下查询应适合您的情况。
--Delete the Referenced Data
DELETE FROM otherTable
WHERE ID IN
(
SELECT ID FROM
(
SELECT ID, ROW_NUMBER() OVER( PARTITION BY column_name ORDER BY ID) RN
FROM tableObj
)T WHERE T.RN>1
)
GO
--DELETING THE DUPLICATE ROWS
WITH CTE AS
(
SELECT ID, ROW_NUMBER() OVER( PARTITION BY column_name ORDER BY ID) RN
FROM tableObj
)
DELETE CTE WHERE RN > 1