/****** Object:  Trigger [dbo].[TRG_EST_PROD_CPL_SEM_ESTOQUE]    Script Date: 23/03/2017 15:12:04 ******/
IF EXISTS( SELECT * FROM SYS.OBJECTS
			WHERE  NAME = 'TRG_EST_PROD_CPL_SEM_ESTOQUE' AND TYPE = 'TR' )
	BEGIN
		DROP TRIGGER DBO.TRG_EST_PROD_CPL_SEM_ESTOQUE;
	END;
GO
---

CREATE TRIGGER [dbo].[TRG_EST_PROD_CPL_SEM_ESTOQUE] ON [dbo].[EST_PROD_CPL]
FOR UPDATE
AS
	 IF UPDATE(QT_EST)
		 BEGIN
			 DELETE FROM EST_PROD_CPL_SEM_ESTOQUE
			 FROM EST_PROD_CPL_SEM_ESTOQUE PROD
				  INNER JOIN INSERTED S ON PROD.CD_EMP = S.CD_EMP
										   AND PROD.CD_FILIAL = S.CD_FILIAL
										   AND PROD.CD_PROD = S.CD_PROD;


			 INSERT INTO EST_PROD_CPL_SEM_ESTOQUE(
												CD_EMP
											  , CD_FILIAL
											  , CD_PROD
											  , DT_ESTOQUE_ZERADO)
			 SELECT
					CD_EMP
				  , CD_FILIAL
				  , CD_PROD
				  , GETDATE()
			 FROM
				 INSERTED S
			 WHERE  S.QT_EST <= 0;


			 INSERT INTO EST_PROD_CUSTO_GRP_PROC_PENDENTE(
					CD_EMP
				  , CD_PROD
				  , DT_CAD)
			 SELECT DISTINCT
					I.CD_EMP
				  , I.CD_PROD
				  , GETDATE() DT_CAD
			 FROM
				 INSERTED I
				 LEFT JOIN EST_PROD_CUSTO_GRP_PROC_PENDENTE P ON 
					I.CD_EMP	= P.CD_EMP AND
					I.CD_PROD	= P.CD_PROD AND 
					GETDATE() 	= P.DT_CAD
			WHERE
				P.CD_EMP IS NULL;

		 END;


