IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_EST_NF_ENT_VINCULO_PBM_CANCELA]') AND type in (N'P', N'PC'))
begin
	DROP PROCEDURE P_EST_NF_ENT_VINCULO_PBM_CANCELA
end
GO
go
--EXEC P_EST_NF_ENT_VINCULO_PBM_CANCELA 1,1,1,1
CREATE PROCEDURE P_EST_NF_ENT_VINCULO_PBM_CANCELA(@CD_EMP INT, @CD_FILIAL INT, @CD_NF INT,@CD_USU INT, @CD_PROD INT)
AS
SET NOCOUNT ON;
SET ANSI_WARNINGS OFF;
DECLARE @CD_CTR INT

SET @CD_CTR= ISNULL((SELECT
						CD_CTR
					FROM
						EST_NF_ENT_DANFE_PROVISORIO_EST_NF_ENT
					WHERE
						CD_EMP = @CD_EMP
						AND CD_FILIAL=@CD_FILIAL 
						AND CD_NF=@CD_NF),0)


IF @CD_CTR>0
BEGIN
	UPDATE 
		EST_NF_ENT_DANFE_PROVISORIO
	SET
		FLAG_REPOSICAO_PBM=0
	WHERE
		CD_CTR=@CD_CTR

	UPDATE 
		EST_NF_ENT
	SET
		FLAG_REPOSICAO_PBM=0
	WHERE
		CD_EMP = @CD_EMP
		AND CD_FILIAL=@CD_FILIAL 
		AND CD_NF=@CD_NF

	DELETE
	FROM 
		EST_NF_ENT_PBM
	WHERE
		CD_EMP = @CD_EMP
		AND CD_FILIAL=@CD_FILIAL 
		AND CD_NF=@CD_NF		

	DELETE
	FROM
		EST_NF_ENT_IT_PBM_GLOSADA
	WHERE
		CD_EMP = @CD_EMP
		AND CD_FILIAL=@CD_FILIAL 
		AND CD_NF=@CD_NF		
		AND CD_PROD = CASE WHEN @CD_PROD > 0 THEN @CD_PROD ELSE CD_PROD END

	INSERT INTO EST_NF_ENT_IT_PBM_GLOSADA (CD_EMP,	CD_FILIAL,	CD_NF,	CD_PROD,	CD_USU,	DT_CAD)
	SELECT
		CD_EMP,
		CD_FILIAL,
		CD_NF,
		CD_PROD,
		@CD_USU,
		GETDATE()
	FROM
		EST_NF_ENT_IT
	WHERE
		CD_EMP = @CD_EMP
		AND CD_FILIAL=@CD_FILIAL 
		AND CD_NF=@CD_NF		
		AND CD_PROD = CASE WHEN @CD_PROD > 0 THEN @CD_PROD ELSE CD_PROD END
END
