IF OBJECT_ID('P_CORRIGE_SEQ_ITEM_DUPLICADO_EST_NF_ENT') IS NOT NULL
BEGIN
	DROP PROCEDURE P_CORRIGE_SEQ_ITEM_DUPLICADO_EST_NF_ENT
END

GO

CREATE PROCEDURE P_CORRIGE_SEQ_ITEM_DUPLICADO_EST_NF_ENT
AS BEGIN

SELECT DISTINCT
	IT.CD_EMP,
	IT.CD_FILIAL,
	IT.CD_NF
INTO 
	#EST_NF_ENT_IT_SEQ_IT_DUP
FROM
	EST_NF_ENT_IT IT
GROUP BY
	IT.CD_EMP,
	IT.CD_FILIAL,
	IT.CD_NF,
	IT.SEQ_ITEM
HAVING
	COUNT(*) > 1

SELECT
	IT.CD_EMP,
	IT.CD_FILIAL,
	IT.CD_NF,
	IT.CD_PROD,
	ROW_NUMBER() OVER (PARTITION BY IT.CD_EMP, IT.CD_FILIAL, IT.CD_NF ORDER BY IT.CD_EMP, IT.CD_FILIAL, IT.CD_NF, IT.CD_PROD) AS SEQ_ITEM
INTO
	#EST_NF_ENT_IT_SEQ_IT_DUP_CORRECAO
FROM
	#EST_NF_ENT_IT_SEQ_IT_DUP D
	INNER JOIN EST_NF_ENT_IT IT ON
		D.CD_EMP = IT.CD_EMP
		AND D.CD_FILIAL = IT.CD_FILIAL
		AND D.CD_NF = IT.CD_NF
ORDER BY 
	D.CD_EMP, 
	D.CD_FILIAL, 
	D.CD_NF

UPDATE
	IT
SET
	IT.SEQ_ITEM = D.SEQ_ITEM
FROM
	#EST_NF_ENT_IT_SEQ_IT_DUP_CORRECAO D
	INNER JOIN EST_NF_ENT_IT IT ON
		D.CD_EMP = IT.CD_EMP
		AND D.CD_FILIAL = IT.CD_FILIAL
		AND D.CD_NF = IT.CD_NF
		AND D.CD_PROD = IT.CD_PROD



DROP TABLE #EST_NF_ENT_IT_SEQ_IT_DUP
DROP TABLE #EST_NF_ENT_IT_SEQ_IT_DUP_CORRECAO

END