IF EXISTS( SELECT * FROM SYS.OBJECTS 
			WHERE NAME ='TRG_EST_PED_CP_IT_CANCEL_SLD_CANCELA_PEDIDO'AND TYPE = 'TR')
BEGIN
	DROP TRIGGER DBO.TRG_EST_PED_CP_IT_CANCEL_SLD_CANCELA_PEDIDO
END
GO

/****** Object:  Trigger [dbo].[TRG_EST_PED_CP_IT_CANCEL_SLD_CANCELA_PEDIDO]    Script Date: 31/07/2015 19:11:46 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
--------------------------------------CANCELAR PEDIDO DE COMPRAS EM EST_PED_CP_IT_CANCEL_SLD--------------------------------------
CREATE TRIGGER [dbo].[TRG_EST_PED_CP_IT_CANCEL_SLD_CANCELA_PEDIDO] ON [dbo].[EST_PED_CP_IT_CANCEL_SLD] FOR INSERT AS
IF CONTEXT_INFO() = 0x99999 
	RETURN
IF EXISTS ( SELECT
					v.CD_CTR
				FROM
					EST_NF_ENT_DANFE_PROVISORIO_EST_PED_CP v 
					INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_PENDENTE pend ON
					v.CD_CTR = pend.CD_CTR
					INNER JOIN INSERTED i ON
					v.CD_EMP = i.CD_EMP AND
					v.CD_FILIAL = i.CD_FILIAL AND
					v.CD_PED = i.CD_PED
	 
					INNER JOIN EST_NF_ENT_DANFE_PROVISORIO_ITENS W ON
					v.CD_EMP = W.CD_EMP AND
					v.CD_CTR = W.CD_CTR AND
					I.CD_PROD = W.CD_PROD   )
begin
	RAISERROR ('Pedido de compras possui vinculo com danfe pendente de entrada.',16, 1); 
	RETURN;
end


GO


