IF NOT EXISTS (SELECT * FROM SYSCOLUMNS INNER JOIN SYSOBJECTS ON SYSOBJECTS.id = SYSCOLUMNS.id 
              WHERE SYSOBJECTS.name = 'SCRIPTBACKUPS')
				SELECT 'HDOSYA_TRG' SCRIPTNAME,OBJECT_DEFINITION(OBJECT_ID('HDOSYA_TRG')) AS SCRIPT,GETDATE() AS SCRIPTDATE INTO SCRIPTBACKUPS
GO

IF OBJECT_ID ('HDOSYA_TRG', 'TR') IS NOT NULL
  DROP TRIGGER HDOSYA_TRG
GO

CREATE TRIGGER [HDOSYA_TRG] ON [dbo].[HDOSYA] 
FOR UPDATE, DELETE
AS
SET NOCOUNT ON


declare @DIFFTBL TABLE(
	ICMALID INT,
	TOPLAMTUTAR FLOAT,
	FATTUTAR FLOAT,
	DOSYASAYISI INT
)
INSERT INTO @DIFFTBL(ICMALID,TOPLAMTUTAR,FATTUTAR,DOSYASAYISI)
SELECT 
	T.ICMALID,
	SUM(KRMNETTUTAR) AS NETTUTAR,
	SUM(KRMFATTUTAR) AS FATTUTAR,
	SUM(DOSYASAYISI) AS DOSYASAYISI
FROM(
	SELECT I.ICMALID,I.KRMNETTUTAR, I.KRMFATTUTAR,1 AS DOSYASAYISI
	FROM inserted I 
	WHERE I.ICMALID IS NOT NULL

	UNION ALL

	SELECT D.ICMALID,-D.KRMNETTUTAR, -D.KRMFATTUTAR,-1 AS DOSYASAYISI
	FROM deleted D 
	WHERE D.ICMALID IS NOT NULL

	UNION ALL

	SELECT I.SGICMALID, I.SGNETTUTAR, I.SGFATTUTAR,1 AS DOSYASAYISI
	FROM inserted I 
	WHERE I.SGICMALID IS NOT NULL

	UNION ALL

	SELECT D.SGICMALID, -D.SGNETTUTAR,  -D.SGFATTUTAR,-1 AS DOSYASAYISI
	FROM deleted D 
	WHERE D.SGICMALID IS NOT NULL
)T
GROUP BY ICMALID
HAVING 
	SUM(KRMNETTUTAR) <> 0 OR
	SUM(KRMFATTUTAR) <> 0 OR
	SUM(DOSYASAYISI) <> 0 

IF EXISTS(SELECT TOP(1) 1 FROM @DIFFTBL)
	UPDATE IC
	SET		
		IC.TOPLAMTUTAR = ISNULL(IC.TOPLAMTUTAR,0) + T.TOPLAMTUTAR,
		IC.FATTUTAR = ISNULL(IC.FATTUTAR,0) + T.FATTUTAR,
		IC.DOSYASAYISI = ISNULL(IC.DOSYASAYISI,0) + T.DOSYASAYISI
	FROM @DIFFTBL T
	INNER JOIN ICMAL IC ON IC.ICMALID = T.ICMALID



GO

