
IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[FATURA_TRG_EFATURA_IPTAL]'))
BEGIN
ALTER TABLE [dbo].[FATURA] DISABLE TRIGGER [FATURA_TRG_EFATURA_IPTAL]
DROP TRIGGER [dbo].[FATURA_TRG_EFATURA_IPTAL]
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF NOT EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[FATURA_TRG_EFATURA_IPTAL]'))
EXEC dbo.sp_executesql @statement = N'
CREATE TRIGGER [dbo].[FATURA_TRG_EFATURA_IPTAL] ON [dbo].[FATURA] FOR UPDATE AS
BEGIN   
   DECLARE @FATID INT, @EFATURADURUM INT, @EDEVLETDURUM INT
   SELECT  @FATID=FATID, @EFATURADURUM=ISNULL(EFATURADURUM,0),@EDEVLETDURUM = ISNULL( EDEVLETDURUM, 0 ) FROM inserted
           SET NOCOUNT ON;

           IF (@EFATURADURUM=5) OR ((@EDEVLETDURUM = 2) AND (@EFATURADURUM=7))
           BEGIN
             UPDATE FATURA SET FIPTAL=1, FIPTALACIKLAMA = ''ENTEGRATÖR''''DEN İPTAL'', FIPTALTARIH = GETDATE() WHERE FATID=@FATID
             UPDATE HESAPISL SET OZELHFATISLID = NULL WHERE OZELHFATISLID = @FATID
             UPDATE HESAPISL SET KRMHFATISLID = NULL WHERE KRMHFATISLID = @FATID
             UPDATE HESAPISL SET SGFATID = NULL WHERE SGFATID = @FATID
           END
        END
' 
GO

IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[FATURA_TRG_EFATURA_IPTAL]'))
ALTER TABLE [dbo].[FATURA] ENABLE TRIGGER [FATURA_TRG_EFATURA_IPTAL]
GO


