--Creating Table dup1
CREATE TABLE dup1
(
cola VARCHAR(10),
colb VARCHAR(10)
);
--Insertion of records
INSERT INTO
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;