Hoje precisei remover os registros duplicados em uma tabela no SQL Server então resvovi criar um script que realiza esse procedimento
--Remove a tabela se já existir IF OBJECT_ID('tempdb..#WorkflowDuplicatedTemp') IS NOT NULL DROP TABLE #WorkflowDuplicatedTemp --Busca todos os registros que estão pulicados e armazena em uma tabela temporária SELECT WorkflowID, EntityKeyValue INTO #WorkflowDuplicatedTemp FROM workflows.task_timed_triggers WHERE Status='W' GROUP BY WorkflowID, EntityKeyValue HAVING COUNT(1) > 1 DECLARE @KeyValue UNIQUEIDENTIFIER DECLARE @WorkflowID INT DECLARE @WorkflowTimedTriggerID INT WHILE EXISTS (SELECT 1 FROM #WorkflowDuplicatedTemp) BEGIN --busca o registro aguardando o processamento SELECT TOP 1 @KeyValue = EntityKeyValue, @WorkflowID = WorkflowID FROM #WorkflowDuplicatedTemp ------------------------------------------------------------------------------- -- verificar se tem um registro com lock date (em processamento) -- deverá manter esse registro, se não houver deverá manter o registro -- aguardando processamento (lock date is null) IF EXISTS( SELECT 1 FROM workflows.task_timed_triggers WHERE WorkflowID = @WorkflowID AND LockDate IS NOT NULL AND EntityKeyValue = @KeyValue AND Status = 'W' ) SELECT TOP 1 @WorkflowTimedTriggerID = WorkflowTimedTriggerID FROM workflows.task_timed_triggers WHERE WorkflowID = @WorkflowID AND LockDate IS NOT NULL AND EntityKeyValue = @KeyValue AND Status = 'W' ELSE SELECT TOP 1 @WorkflowTimedTriggerID = WorkflowTimedTriggerID FROM workflows.task_timed_triggers WHERE WorkflowID = @WorkflowID AND LockDate IS NULL AND EntityKeyValue = @KeyValue AND Status = 'W' --END -- Deleta os registros duplicados, mantendo um registro aguardando processamento DELETE FROM workflows.task_timed_triggers WHERE EntityKeyValue=@KeyValue AND Status='W' AND WorkflowID=@WorkflowID AND WorkflowTimedTriggerID != @WorkflowTimedTriggerID -- Deleta o registro da tabela temporaria DELETE FROM #WorkflowDuplicatedTemp WHERE WorkflowID = @WorkflowID AND EntityKeyValue = @KeyValue END
Deixe um comentário