SQL Server 2008 R2: Delete duplicate rows from tables containing in view

前端 未结 4 605
孤街浪徒
孤街浪徒 2021-01-17 02:45

--Creating Table dup1

CREATE TABLE dup1
(
    cola VARCHAR(10),
    colb VARCHAR(10)
);

--Insertion of records

INSERT INTO          


        
4条回答
  •  情歌与酒
    2021-01-17 03:19

    Create a temp table with the rows need to be deleted from CTE and delete those from both the tables.

    Query

    CREATE TABLE dup1
    (
        cola VARCHAR(10),
        colb VARCHAR(10)
    );
    
    INSERT INTO dup1 VALUES('1','2');
    INSERT INTO dup1 VALUES('1','2');
    INSERT INTO dup1 VALUES('1','3');
    INSERT INTO dup1 VALUES('1','4');
    INSERT INTO dup1 VALUES('1','5');
    
    CREATE TABLE dup2
    (
        cola VARCHAR(10),
        colb VARCHAR(10)
    );
    
    INSERT INTO dup2 VALUES('1','2');
    INSERT INTO dup2 VALUES('1','2');
    INSERT INTO dup2 VALUES('2','3');
    INSERT INTO dup2 VALUES('2','4');
    INSERT INTO dup2 VALUES('1','5');
    
    CREATE VIEW V_Dup as
    SELECT * FROM dup1 UNION ALL
    SELECT * FROM dup2;
    
    ;with cte as 
    (
        select rn=row_number() over
        (
            partition by cola,colb
            order by cola,colb
        ),*
        from V_Dup
    )
    select * into #temp
    from cte 
    where rn>1;
    
    delete t1 from dup1 t1
    inner join  #temp t2
    on t1.cola = t2.cola
    and t1.colb = t2.colb;
    
    delete t1 from dup2 t1
    inner join  #temp t2
    on t1.cola = t2.cola
    and t1.colb = t2.colb;
    
    drop table #temp;
    

提交回复
热议问题