/****** Object:  Trigger [dbo].[TRG_RC_DEB_IMP_PEND]    Script Date: 09/08/2017 09:44:47 ******/
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
IF EXISTS(SELECT * FROM sys.triggers
	WHERE object_id = OBJECT_ID(N'[dbo].[TRG_RC_DEB_IMP_PEND]'))
	DROP TRIGGER [dbo].[TRG_RC_DEB_IMP_PEND];
 GO

CREATE TRIGGER [dbo].[TRG_RC_DEB_IMP_PEND] ON [dbo].[RC_DEB]
AFTER INSERT, UPDATE
AS
    INSERT INTO RC_DEB_IMPRESSAO_PENDENTE(CD_EMP,CD_FILIAL,CD_RC_DEB,DT_CAD)
    SELECT 
	   I.CD_EMP,
	   I.CD_FILIAL,
	   I.CD_RC_DEB,
	   ISNULL(I.DT_CAD,GETDATE())
    FROM 
	   INSERTED I
    WHERE 
	   NOT EXISTS(SELECT CD_EMP
				FROM RC_DEB_IMPRESSAO_PENDENTE A
				WHERE A.CD_EMP = I.CD_EMP
					   AND A.CD_FILIAL = I.CD_FILIAL
					   AND A.CD_RC_DEB = I.CD_RC_DEB)
        AND STS_DP <> 3;
GO


