IF  NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[EST_NF_ENT_PRE_ENTRADA_EST_WMS_ENT]') 
					AND name = N'UX_EST_NF_ENT_PRE_ENTRADA_EST_WMS_ENT_CD_PED_WMS')
begin 

DECLARE @chave INT
DECLARE cDelete CURSOR FAST_FORWARD FOR
	SELECT
		cd_ped_wms
	FROM
		EST_NF_ENT_PRE_ENTRADA_EST_WMS_ENT
	GROUP  BY
		cd_ped_wms
	HAVING
		COUNT(*) > 1

OPEN cDelete

FETCH NEXT FROM cDelete INTO @chave

WHILE @@FETCH_STATUS = 0
	BEGIN
			PRINT 'Deleta chave ' + CONVERT(VARCHAR, @chave)

			WHILE EXISTS(SELECT
										 CD_PED_WMS
									 FROM
										 EST_NF_ENT_PRE_ENTRADA_EST_WMS_ENT
									 WHERE
										CD_PED_WMS = @chave
									 GROUP  BY
										CD_PED_WMS
									 HAVING
										COUNT(*) > 1)
				BEGIN
						DELETE FROM EST_NF_ENT_PRE_ENTRADA_EST_WMS_ENT
						WHERE  CD_CTR_PRE_ENTRADA = (SELECT
																					 MAX(CD_CTR_PRE_ENTRADA)
																				 FROM
																					 EST_NF_ENT_PRE_ENTRADA_EST_WMS_ENT
																				 WHERE
																					cd_ped_wms = @chave);
				END

			FETCH NEXT FROM cDelete INTO @chave
	END

	CLOSE cDelete;
	DEALLOCATE cDelete; 

	ALTER TABLE [dbo].[EST_NF_ENT_PRE_ENTRADA_EST_WMS_ENT] 
		ADD CONSTRAINT [UX_EST_NF_ENT_PRE_ENTRADA_EST_WMS_ENT_CD_PED_WMS] UNIQUE NONCLUSTERED 
		([CD_EMP] ASC, [CD_PED_WMS] ASC) WITH 
	(PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,  
			SORT_IN_TEMPDB = OFF, 
			IGNORE_DUP_KEY = OFF, 
			ONLINE = OFF, 
			ALLOW_ROW_LOCKS = ON, 
			ALLOW_PAGE_LOCKS = ON) 
	  ON [PRIMARY]
end