Tuesday, March 11, 2014

How to delete duplicate records in SQL Server


To delete any duplicate records in SQL Server

create table t1 (col1 int, col2 int)

insert into t1 values ( 1, 70)
insert into t1 values ( 1, 70)
insert into t1 values ( 1, 71)
insert into t1 values ( 1, 72)
insert into t1 values ( 1, 72)
insert into t1 values ( 1, 73)
insert into t1 values ( 1, 74)
insert into t1 values ( 1, 75)

select * from t1

with t1dups (col1, coldups)
AS (
select col2, ROW_NUMBER() Over (Partition by col1, col2 order by col2) as dups from t1 )
delete from t1dups where coldups > 1

select * from t1

No comments: