How can I delete duplicate rows in a table

后端 未结 13 1376
情歌与酒
情歌与酒 2020-12-08 22:30

I have a table with say 3 columns. There\'s no primary key so there can be duplicate rows. I need to just keep one and delete the others. Any idea how to do this is Sql Serv

13条回答
  •  失恋的感觉
    2020-12-08 23:21

    What about this solution :

    First you execute the following query :

      select 'set rowcount ' + convert(varchar,COUNT(*)-1) + ' delete from MyTable where field=''' + field +'''' + ' set rowcount 0'  from mytable group by field having COUNT(*)>1
    

    And then you just have to execute the returned result set

    set rowcount 3 delete from Mytable where field='foo' set rowcount 0
    ....
    ....
    set rowcount 5 delete from Mytable where field='bar' set rowcount 0
    

    I've handled the case when you've got only one column, but it's pretty easy to adapt the same approach tomore than one column. Let me know if you want me to post the code.

提交回复
热议问题