Thursday, August 30, 2018

Remove Duplicate data from table, SQL Server



SELECT * into #temp2  FROM [vislidb].[dbo].[Employees]
--Create Duplicate data in #temp2
insert into #temp2
SELECT *   FROM [vislidb].[dbo].[Employees] where EmployeeID=1

--Get count , find dups and put in a temp table
SELECT EmployeeID,count(EmployeeID)CountEmployeeID  into #temp3 FROM #temp2
group by EmployeeID
having  count(EmployeeID)>1

--put non dup data  in a temp table using distinct
select distinct * into #temp4 from #temp2 where EmployeeID in(
select EmployeeID from #temp3)

--delete dups from temp table
delete  from #temp2 where EmployeeID in(
select EmployeeID from #temp3)

-- insert from non dup table
insert into #temp2
select * from #temp4

select * from #temp2