方法:
| 代码如下 |
复制代码 |
select distinct * into #tmp from tablename drop table tablename select * into tablename from #tmp
drop table # tmp |
常有时候遇到需要删除SQL Server中的重复记录,这里有一些常用的删除重复记录的SQL,
最常用的 T-SQL 语句:
| 代码如下 |
复制代码 |
|
DELETE FROM [dbo].[myTable] WHERE 主键 NOT IN
(SELECT MAX(主键) FROM [dbo].[myTable] GROUP BY 列1, 列2, 列3)从 SQL Server 2005 以后,用 CTE:
WITH tmpOrderdTable
AS
(
SELECT
GroupID = ROW_NUMBER() OVER (PARTITION BY 列1, 列2, 列3 ORDER BY 主键)
FROM
[dbo].[myTable]
)
DELETE FROM tmpOrderdTable WHERE GroupID > 1
|
为了提高效率可以先开启单人存取模式,删除完再恢复多人存取模式:
# 开启单人存取模式
| 代码如下 |
复制代码 |
|
USE [master]
ALTER DATABASE [myDB] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
# 开启多人存取模式
USE [master]
ALTER DATABASE [myDB] SET MULTI_USER WITH ROLLBACK IMMEDIATERelated Posts
|
SQL存储过程删除
| 代码如下 |
复制代码 |
|
declare @max integer,@id integer
declare cur_rows cursor local for select 主字段,count(*) from 表名 group by 主字段 having count(*) > 1
open cur_rows
fetch cur_rows into @id,@max
while @@fetch_status=0
begin
select @max = @max -1
set rowcount @max
delete from 表名 where 主字段 = @id
fetch cur_rows into @id,@max
end
close cur_rows
set rowcount 0
|
A:保留id最大的行,删除其它行
方法1
| 代码如下 |
复制代码 |
|
delete [user] from [user] t
inner join(select name,max(id) as id from [user] group by name) a
on t.name = a.name and t.id <> a.id
|
B:保留id最小的行,删除其它行
方法1
| 代码如下 |
复制代码 |
delete [user] from [user] t
inner join(select name,min(id) as id from [user] group by name) a
on t.name = a.name and t.id <> a.id
|