IF EXISTS (
		SELECT *
		FROM sys.objects
		WHERE object_id = OBJECT_ID(N'[dbo].[P_EST_NF_ENT_DANFE_PROVISORIO_ITENS_VALIDACAO_IMPOSTO_REPROCESSAMENTO]')
			AND type IN (N'P', N'PC')
		)
	DROP PROCEDURE [dbo].[P_EST_NF_ENT_DANFE_PROVISORIO_ITENS_VALIDACAO_IMPOSTO_REPROCESSAMENTO]
GO

CREATE PROCEDURE P_EST_NF_ENT_DANFE_PROVISORIO_ITENS_VALIDACAO_IMPOSTO_REPROCESSAMENTO @CD_CTR INT
AS
BEGIN
	DELETE
	FROM EST_NF_ENT_DANFE_PROVISORIO_ITENS_VALIDACAO_IMPOSTO
	WHERE CD_CTR = @CD_CTR

	DELETE
	FROM EST_NF_ENT_DANFE_PROVISORIO_ITENS_VALIDACAO_IMPOSTO_ERROS_VALIDACAO
	WHERE CD_CTR = @CD_CTR

	DELETE
	FROM EST_NF_ENT_DANFE_PROVISORIO_VALIDACAO_IMPOSTO_CONFIRMACAO
	WHERE CD_CTR = @CD_CTR

	DELETE
	FROM EST_NF_ENT_DANFE_PROVISORIO_ITENS_VALIDACAO_IMPOSTO_PENDENTE
	WHERE CD_CTR = @CD_CTR

	INSERT INTO EST_NF_ENT_DANFE_PROVISORIO_ITENS_VALIDACAO_IMPOSTO_PENDENTE
	SELECT EST_NF_ENT_DANFE_PROVISORIO_ITENS.CD_CTR
		,EST_NF_ENT_DANFE_PROVISORIO_ITENS.CD_CTR_IT
		,GETDATE() AS DT_CAD
	FROM EST_NF_ENT_DANFE_PROVISORIO_ITENS
	LEFT JOIN EST_NF_ENT_DANFE_PROVISORIO_SUSPENSO ON EST_NF_ENT_DANFE_PROVISORIO_ITENS.CD_CTR = EST_NF_ENT_DANFE_PROVISORIO_SUSPENSO.CD_CTR
	WHERE EST_NF_ENT_DANFE_PROVISORIO_ITENS.CD_CTR = @CD_CTR
		AND EST_NF_ENT_DANFE_PROVISORIO_SUSPENSO.CD_CTR IS NULL
END
