IF OBJECT_ID('P_EST_SNGPC_SAIDA_TRANSF_EXCLUIR') IS NOT NULL
	BEGIN
		DROP PROCEDURE P_EST_SNGPC_SAIDA_TRANSF_EXCLUIR;
	END;
GO

CREATE PROCEDURE P_EST_SNGPC_SAIDA_TRANSF_EXCLUIR(@PCODIGOMOVTRANSFERENCIA INT)
AS
	
	
	 SET NOCOUNT ON; 

	 DECLARE
			@CD_EMP INT;
	 DECLARE
			@CD_FILIAL INT;
	 DECLARE
			@CD_LOTE INT;
	 DECLARE
			@QTDE INT;
	 DECLARE
			@CD_USU INT;
	 DECLARE
			@ERROR VARCHAR(MAX);


	BEGIN TRY
		SELECT @CD_EMP = CD_EMP
			 , @CD_FILIAL = CD_FILIAL
			 , @CD_LOTE = CD_LOTE
			 , @QTDE = QT_LOTE
			 , @CD_USU = CD_USU
		FROM EST_SNGPC_SAIDA
		WHERE CD_SAI_SNGPC = @PCODIGOMOVTRANSFERENCIA;
		DELETE FROM EST_SNGPC_SAIDA
		WHERE CD_SAI_SNGPC = @PCODIGOMOVTRANSFERENCIA;
		UPDATE EST_PROD_EST_SNGPC_LOTE_CPL
		  SET
			  QT_LOTE = (QT_LOTE + @QTDE)
		WHERE CD_EMP = @CD_EMP
			  AND CD_FILIAL = @CD_FILIAL
			  AND CD_LOTE = @CD_LOTE;
		INSERT INTO SNGPC_HIST_MOV_LOTE
		(CD_EMP
	   , CD_FILIAL
	   , CD_PROD
	   , LOTE
	   , TIPO_MOV
	   , CD_MOV
	   , DT_MOV
	   , CD_USU
	   , QT_MOV
		)
		VALUES
		(@CD_EMP
	   , @CD_FILIAL
	   , 0
	   , @CD_LOTE
	   , 'EXCLUSAO MOV.TRANSFERENCIA'
	   , @PCODIGOMOVTRANSFERENCIA
	   , GETDATE()
	   , @CD_USU
	   , @QTDE
		);
	END TRY
	BEGIN CATCH
		BEGIN TRY
			ROLLBACK;
		END TRY
		BEGIN CATCH
		END CATCH;
		SET @ERROR = ERROR_MESSAGE();
		RAISERROR(@ERROR, 16, 1);
	END CATCH;