开发者社区> 问答> 正文

使用临时表删除其他表中的重复行及其依赖项

使用临时表删除其他表中的重复行及其依赖项

展开
收起
贺贺_ 2019-12-02 23:01:23 393 0
1 条回答
写回答
取消 提交回答
  • create table dbo.hasduplicates
    (
        id int identity,
        --assume colA, colB is the entity/unique combo
        colA varchar(10),
        colB int,
        someOtherColumn varchar(40)
    );
    
    
    insert into dbo.hasduplicates(colA, colB, someOtherColumn)
    values
    ('A', 1, 'A1 - 1'),
    ('A', 1, 'A1 - 2'),
    ('A', 1, 'A1 - 3'),
    --
    ('A', 2, 'A2 - 1'),
    ('A', 2, 'A2 - 2'),
    --
    ('B', 1, 'B1 - 1'),
    ('B', 1, 'B1 - 2'),
    ('B', 1, 'B1 - 3');
    
    
    select *
    from dbo.hasduplicates;
    
    
    --temp table holding the to-be-deleted ids (of the duplicates)
    create table #ToBedeleted(IdToDelete int);
    
    with dup
    as
    (
        select *, row_number() over (partition by colA, colB /*<--cols of your entity go here*/ order by id) as RowNum
        from dbo.hasduplicates
    )
    insert into #ToBedeleted(IdToDelete)
    select Id
    from dup
    where RowNum >= 2;
    
    --contains the ids for deletion
    select * from #ToBedeleted;
    
    --cleanup the referencing tables
    /*
    DELETE FROM dbo.Table1 WHERE Table1Id IN (SELECT IdToDelete FROM #ToBedeleted);
    DELETE FROM dbo.Table2 WHERE Table2Id IN (SELECT IdToDelete FROM #ToBedeleted);
    .............
    DELETE FROM dbo.Table6 WHERE Table6Id IN (SELECT IdToDelete FROM #ToBedeleted);
    --finally cleanup your products table
    DELETE FROM dbo.hasduplicates WHERE Id IN (SELECT IdToDelete FROM #ToBedeleted);
    */
    
    --/*
    drop table #ToBedeleted;
    drop table dbo.hasduplicates;
    --*/
    
    2019-12-02 23:02:36
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载