if 3 duplicate records in table,i want to delete 2 alternating
duplicate records by keeping 1 duplicate and 1 original as it
is,how?

Answers were Sorted based on User's Feedback



if 3 duplicate records in table,i want to delete 2 alternating duplicate records by keeping 1 dupl..

Answer / mohamed ibrahim

Deleting multiple duplicate rows in a table
Ex . I have the Table named as TestMaster
to delete duplicate rows from the testmaster using Cursor &
RANK() Function.
for ex.the table having the fields ID,Name
the having the following data
oupput:
ID NAME
1 Raja
1 Raja
1 Raja
2 Mohamed
2 Mohamed
2 Mohamed

To Delete duplicate Rows in table to follow the below code:

DECLARE @ID INT
DECLARE delduplicaterecords_Cursor CURSOR
FOR SELECT ID FROM TempMaster
OPEN delduplicaterecords_Cursor
FETCH NEXT FROM delduplicaterecords_Cursor INTO @ID

WHILE @@FETCH_STATUS = 0
BEGIN
WITH CTE
AS
(SELECT
ROW_NUMBER () OVER (ORDER BY ID) AS RowID,
*
FROM TempMaster WHERE ID=@ID )

DELETE FROM CTE WHERE RowID <> 1

FETCH NEXT FROM delduplicaterecords_Cursor INTO @ID
END

CLOSE delduplicaterecords_Cursor
DEALLOCATE delduplicaterecords_Cursor

Is This Answer Correct ?    0 Yes 0 No

if 3 duplicate records in table,i want to delete 2 alternating duplicate records by keeping 1 dupl..

Answer / sivam

sno sname salary
1 aaa 1000
1 aaa 1000
2 bbb 2000
2 bbb 2000
2 bbb 2000
1 aaa 1000

;with aa as
(
select sname,salary,ROW_NUMBER()over(partition by sno,sname,salary order by sno,sname,salary) as Nos from #testtable
)

delete from aa where Nos%2<>0

Is This Answer Correct ?    0 Yes 0 No

Post New Answer

More SQL Server Interview Questions

What is the impact on other user sessions when creating indexes?

0 Answers  


how to get 25th row in any table in sqlserver can u tell me syntax

8 Answers  


you accidentally delete the msdb database what effect does this have on your existing sql databases, and how do you recover? : Sql server administration

0 Answers  


what is an extended stored procedure? Can you instantiate a com object by using t-sql? : Sql server database administration

0 Answers  


What is a trigger and its types?

0 Answers  






What is cte (common table expression)?

0 Answers  


Explain what are the events recorded in a transaction log?

0 Answers  


Difference between DELETE and TRUNCATE?

0 Answers   TCS,


difference between select column name from table name where serviceid=2; and select max(column name) from table name where serviceid=2; IN ORACLE

3 Answers   Intel, Wipro,


Explain about SQL server 2005?

0 Answers  


What is right outer join in sql server joins?

0 Answers  


What is the difference between a local and a global variable?

5 Answers  


Categories