Jul 30, 2011

How to delete duplicate records from a table in sql server

It is not possible to insert duplicate records in a table if using primary key constraints.But in relational database when foreign key is used it is possible that a duplicate records can insert in foreign key column.So solving that type of condition use that statement.
Example:

set rowcount

delete from table_name

where column_name=values

set rowcount 0

To delete all the duplicate rows you need to write a cursor as

DECLARE @id int
DECLARE @name nvarchar(50)
DECLARE @count int

DECLARE CUR_DELETE CURSOR FOR
SELECT [id],[name],COUNT([id]) FROM [table_name] GROUP BY [id],[name] HAVING COUNT([id]) > 1

OPEN CUR_DELETE

FETCH NEXT FROM CUR_DELETE INTO @id,@name,@count
/* Loop through cursor for remaining ID */
WHILE @@FETCH_STATUS = 0
BEGIN

DELETE TOP(@COUNT -1) FROM [table_name] WHERE ID = @id

FETCH NEXT FROM CUR_DELETE INTO @id,@name,@count
END

CLOSE CUR_DELETE
DEALLOCATE CUR_DELETE

No comments:

Post a Comment