How to delete duplicate rows in SQL Server?

后端 未结 23 1402
长情又很酷
长情又很酷 2020-11-22 00:58

How can I delete duplicate rows where no unique row id exists?

My table is

col1  col2 col3 col4 col5 col6 col7
john  1          


        
23条回答
  •  孤独总比滥情好
    2020-11-22 01:37

    It can be done by many ways in sql server the most simplest way to do so is: Insert the distinct rows from the duplicate rows table to new temporary table. Then delete all the data from duplicate rows table then insert all data from temporary table which has no duplicates as shown below.

    select distinct * into #tmp From table
       delete from table
       insert into table
       select * from #tmp drop table #tmp
    
       select * from table
    

    Delete duplicate rows using Common Table Expression(CTE)

    With CTE_Duplicates as 
    (select id,name , row_number() 
    over(partition by id,name order by id,name ) rownumber  from table  ) 
    delete from CTE_Duplicates where rownumber!=1
    

提交回复
热议问题