IF  EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[P_EST_NF_ENT_IT_DEVOLUCAO_ANALISE_SALDO]') AND TYPE IN (N'P', N'PC'))
DROP PROCEDURE [DBO].[P_EST_NF_ENT_IT_DEVOLUCAO_ANALISE_SALDO]
GO
GO
CREATE PROCEDURE P_EST_NF_ENT_IT_DEVOLUCAO_ANALISE_SALDO (@CD_EMP INT, @CD_FILIAL INT, @CD_NF INT)
AS
UPDATE	
	d
SET 
	d.QTDE_PROD_DEVO_GERADA= CASE WHEN V_EST_NF_ENT_IT_DEV_SLD.QT_SLD_IT = d.QTDE_PROD THEN
		0
	ELSE
		CASE WHEN V_EST_NF_ENT_IT_DEV_SLD.QT_SLD_IT > d.QTDE_PROD THEN
			0
		ELSE
			d.QTDE_PROD-V_EST_NF_ENT_IT_DEV_SLD.QT_SLD_IT
		END
	END 
FROM
	V_EST_NF_ENT_IT_DEV_SLD INNER JOIN EST_NF_ENT_IT_DEVOLUCAO d ON
	V_EST_NF_ENT_IT_DEV_SLD.CD_EMP = d.CD_EMP AND
	V_EST_NF_ENT_IT_DEV_SLD.CD_FILIAL = d.CD_FILIAL AND
	V_EST_NF_ENT_IT_DEV_SLD.CD_NF = d.CD_NF AND
	V_EST_NF_ENT_IT_DEV_SLD.CD_PROD = d.CD_PROD 
WHERE
	V_EST_NF_ENT_IT_DEV_SLD.CD_EMP =@CD_EMP
	AND V_EST_NF_ENT_IT_DEV_SLD.CD_FILIAL = @CD_FILIAL
	AND V_EST_NF_ENT_IT_DEV_SLD.CD_NF = @CD_NF
	AND V_EST_NF_ENT_IT_DEV_SLD.QT_SLD_IT > 0