create trigger ACariBakiyeUpdate
on ACARI
after UPDATE, INSERT, DELETE
as
declare @MUSNO int
if exists(SELECT * from inserted) and exists (SELECT * from deleted)
begin   
    SELECT @MUSNO = MUSNO from inserted i;    
end

If exists (Select * from inserted) and not exists(Select * from deleted)
begin
    SELECT @MUSNO = MUSNO from inserted i;    
end

If exists(select * from deleted) and not exists(Select * from inserted)
begin     
    SELECT @MUSNO = MUSNO from deleted i;   
end

UPDATE m SET m.MUSBORC   = BORC,
			 m.MUSALACAK = ALACAK, 
			 m.MUSBAKIYE = BAKIYE 
  from AMUSTERI m ,
	   (Select MUSNO,SUM(BORC) BORC,SUM(ALACAK) ALACAK,SUM(BORC - ALACAK) BAKIYE from ACARI GROUP BY MUSNO) c
 where c.MUSNO = m.MUSNO 
   and  c.MUSNO = @MUSNO 
   AND NOT EXISTS ( select 'x' from KullaniciAyarlari k where Ayar = 'PesinCariNo' AND Deger = m.MUSNO)
