是否可以在不知道表列的情况下从表中删除重复的行?

时间:2019-05-25 21:14:44

标签: sql oracle

当您仅使用普通SQL(不使用PL / SQL)不知道表的结构(列)时,是否可以从数据库的任意表中删除所有重复的行?

-- The code should look something like this
DELETE FROM tableName -- tableName can be changed
WHERE ...

因此,以下表为例:

.-------.
| A | B |
|---|---|
| 1 | 1 | -- (1)
| 2 | 1 | -- (2)
| 2 | 1 | -- (3) duplicate of (2)
| 3 | 2 | -- (4)
| 3 | 2 | -- (5) duplicate of (4)
| 3 | 2 | -- (6) duplicate of (4)
'-------'

结果应如下:

.-------.
| A | B |
|---|---|
| 1 | 1 | -- (1)
| 2 | 1 | -- (2)
| 3 | 2 | -- (4)
'-------'

1 个答案:

答案 0 :(得分:1)

SELECT distinct * from TableA INTO TableB; 
truncate TableA;
insert into TableA select * from tableB;
drop tableB;

评论的其他答案:

建立CTE(使用参数化的SQL和信息模式动态构建此CTE)

;WITH cteExample (val1, val2, RN) as 
( select *, ROW_NUMBER() over (PARTITION by val1, val2 order by val1, val2) as RN from tableA) 
-- select * from cteExample -- to verify results
delete from cteExample where RN > 1 -- to delete duplicate records

如果您知道表将具有主键(应按需使用),则使用“不重复”

;WITH cteExample as (select distinct * from TableA) delete a from cteExample b right join TableA a on b.primaryKey = a.PrimaryKey where b.PrimaryKey is null;

最后,如果需要,请完全跳过CTE:

delete a from TableA a left join (select distinct * from TableA) b on a.PK = b.PK 
where b.PK is null

最好使用存储过程或等效的exec sp_executeSQL(如果可用)的等效项动态构建所有这些语句,以便在不了解列的情况下获取列名。