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

CREATE PROCEDURE P_EST_SNGPC_SAIDA_VENDA_EXCLUIR(@CODIGO INT)
AS
	 
	 SET NOCOUNT ON; 

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

	 DECLARE
			@CD_USU INTEGER;

	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 = @CODIGO;

		DELETE FROM EST_SNGPC_SAIDA
		WHERE CD_SAI_SNGPC = @CODIGO;

		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.SAIDA'
	   , @CODIGO
	   , 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;