deleting duplicates  

Posted in ,

Deleting dublicate values from any table in SQL Server.
Key value (ID) may be changed.



SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[delete_dublicates_from_table]
@table nvarchar(255)
as begin
DECLARE @ID bigint
DECLARE @COUNT int
declare @query nvarchar(max)
declare @condamne table (
ids bigint,
counts int
)
set @query = 'SELECT [ID], COUNT([ID]) FROM '+@table+' GROUP BY [ID] HAVING COUNT([ID]) > 1 '
insert into @condamne exec sp_executesql @query
DECLARE CUR_DELETE CURSOR FOR
select * from @condamne
OPEN CUR_DELETE
declare @temp_query nvarchar(max)
FETCH NEXT FROM CUR_DELETE INTO @ID,@COUNT
WHILE @@FETCH_STATUS = 0
BEGIN
set @temp_query = (select 'DELETE TOP('+convert(nvarchar(3),@COUNT,120)+'-1) FROM '+@table+' WHERE ID = '+convert(nvarchar(32), @ID)+' ')
exec sp_executesql @temp_query
FETCH NEXT FROM CUR_DELETE INTO @ID,@COUNT
END
CLOSE CUR_DELETE
DEALLOCATE CUR_DELETE
end

0 responzez

Post a Comment

metanews


Add to Google