/****** Object:  Trigger [TRG_EST_PROD_CPL_TRIB_ST_CRED_QT_IT_SLD_RET]    Script Date: 20/08/2014 11:59:12 ******/
IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[TRG_EST_PROD_CPL_TRIB_ST_CRED_QT_IT_SLD_RET]'))
DROP TRIGGER [dbo].[TRG_EST_PROD_CPL_TRIB_ST_CRED_QT_IT_SLD_RET]
GO
GO
GO
CREATE TRIGGER TRG_EST_PROD_CPL_TRIB_ST_CRED_QT_IT_SLD_RET ON EST_PROD_CPL_TRIB_ST_DEB_EST_PROD_CPL_TRIB_ST_CRED
FOR DELETE
AS 
	BEGIN 
			
		UPDATE CRED SET 
			QT_IT_SLD = (CASE WHEN (CRED.QT_IT_SLD + DEB.QT_IT) > CRED.QT_IT THEN CRED.QT_IT ELSE (CRED.QT_IT_SLD + DEB.QT_IT) END)
		FROM DELETED D
			INNER JOIN EST_PROD_CPL_TRIB_ST_DEB DEB ON 
				D.CD_CTR = DEB.CD_CTR
			INNER JOIN EST_PROD_CPL_TRIB_ST_CRED CRED ON 
				D.CD_CTR_CRED = CRED.CD_CTR
				
	END