Write a query to delete duplicate records in SQL SERVER

Answer Posted / sumit

I have The Same Problem And I Have Done Woth This


DECLARE @empid int, @empname varchar(50),@Cnt int

DECLARE duplicate_cursor CURSOR FOR

-- select all columns in table bit you must have an count column
select empid,empname, count(*) Cnt
from tbl_Temp
group by empid, empname
Having count(*) > 1

OPEN duplicate_cursor

FETCH NEXT FROM duplicate_cursor
INTO @empid, @empname,@Cnt

WHILE @@FETCH_STATUS = 0
BEGIN

SET @Cnt = @Cnt - 1

SET ROWCOUNT @Cnt

DELETE tbl_Temp
WHERE @empid = empid AND @empname = empname


FETCH NEXT FROM duplicate_cursor
INTO @empid, @empname
END

CLOSE duplicate_cursor
DEALLOCATE duplicate_cursor

-- dont forget to set rowcount to 0
SET ROWCOUNT 0

Is This Answer Correct ?    10 Yes 6 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Explain partitioned view?

591


What are ddl (data definition language) statements for tables in ms sql server?

546


What is user-defined scalar function?

558


What is the difference between nvl and nvl2?

552


Mention a few common trace flags used with sql server?

544






How to Insert multiple rows with a single insert statement?

549


What are the export options of ssrs?

126


how would you troubleshoot blocking? : Sql server database administration

523


Explain how to use linked server?

568


How to delete duplicate rows in sql server?

577


How to add additional conditions in SQL?

590


How to retrieve error messages using odbc_errormsg()?

542


What is an index in a database?

537


Which are the third-party tools used in sql server and why would you use them?

493


How to connect to SQL Azure Database by using sqlcmd?

110