IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[P_EST_NF_ENT_VINCULO_PBM_INSERIR]') AND type in (N'P', N'PC'))
begin
	DROP PROCEDURE P_EST_NF_ENT_VINCULO_PBM_INSERIR
end
GO
go
--EXEC P_EST_NF_ENT_VINCULO_PBM_INSERIR 1,1,1,1
CREATE PROCEDURE P_EST_NF_ENT_VINCULO_PBM_INSERIR(@CD_EMP INT, @CD_FILIAL INT, @CD_NF INT,@CD_USU INT,@CD_CONV 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=1
	WHERE
		CD_CTR=@CD_CTR

	UPDATE 
		EST_NF_ENT
	SET
		FLAG_REPOSICAO_PBM=1
	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

	INSERT INTO EST_NF_ENT_PBM
	(CD_EMP,
	CD_FILIAL,
	CD_NF,
	CD_CONV,
	CD_USU,
	DT_CAD)
	SELECT
		@CD_EMP,
		@CD_FILIAL,
		@CD_NF,
		@CD_CONV,
		@CD_USU,
		GETDATE()
END
