DECLARE @FATID INT = (SELECT MIN(FATID)-1 FROM FATURA WHERE KYTARIH>(CONVERT(VARCHAR,YEAR(DATEADD(MONTH,-2,GETDATE()))) + '-' + RIGHT('0'+CONVERT(VARCHAR,MONTH(DATEADD(MONTH,-2,GETDATE()))),2) + '-01'))
UPDATE FATISL SET  KDVTUTAR=0 WHERE FATID>@FATID AND KDVLITOPLAM IS NULL AND (SELECT COUNT(FATID) FROM FATURA WHERE FATURA.FATID=FATISL.FATID AND FATURA.TURADI='PERAKENDE')>0
UPDATE FATISL SET  NETTOPLAM= DBO.fn_RoundBanker(ADET*BFIYAT,2) - DBO.fn_IndirimTutar3lu(DBO.fn_RoundBanker(ADET*BFIYAT,2),SATIRIND,0,SATIRIND2,0,0,SATIRINDT) WHERE FATID>@FATID AND NETTOPLAM IS NULL
UPDATE FATISL SET  KDVTUTAR= DBO.fn_RoundBanker(ISNULL((CASE WHEN ISNULL(KDVTUTAR,0)=0 THEN ISNULL(NETTOPLAM,0)*KDV/100 ELSE KDVTUTAR END),0),2) WHERE FATID>@FATID AND KDVLITOPLAM IS NULL
UPDATE FATISL SET  INDTOPLAM= DBO.fn_IndirimTutar3lu(DBO.fn_RoundBanker(ADET*BFIYAT,2),SATIRIND,0,SATIRIND2,0,0,SATIRINDT) WHERE FATID>@FATID AND KDVLITOPLAM IS NULL AND INDTOPLAM IS NULL

UPDATE FATISL SET 
    OTVMATRAH=0,
    OTVORAN=0,
    OTVTUTAR=0, 
    KDVMATRAH = DBO.fn_RoundBanker(ISNULL((CASE WHEN ISNULL(KDVMATRAH,0)=0 THEN (CASE WHEN NETTOPLAM IS NOT NULL AND ISNULL(NETTOPLAM,0)-ISNULL(INDTOPLAM,0)>0 THEN ISNULL(NETTOPLAM,0)-ISNULL(INDTOPLAM,0) ELSE ISNULL(NETTOPLAM,0) END) ELSE ISNULL(KDVMATRAH,0) END),0),2),
    KDVTUTARI= DBO.fn_RoundBanker(ISNULL((CASE WHEN ISNULL(KDVTUTARI,0)=0 THEN KDVTUTAR ELSE KDVTUTARI END),0),2), 
    YUVARLANANKDVTUTAR=0, 
    KDVLITOPLAM = DBO.fn_RoundBanker(ISNULL((CASE WHEN ISNULL(KDVLITOPLAM,0)=0 THEN (CASE WHEN NETTOPLAM IS NOT NULL AND ISNULL(NETTOPLAM,0)-ISNULL(INDTOPLAM,0)+ISNULL(KDVTUTAR,0)-ISNULL(TEVKIFATTUTARI,0)>0 THEN ISNULL(NETTOPLAM,0)-ISNULL(INDTOPLAM,0)+ISNULL(KDVTUTAR,0)-ISNULL(TEVKIFATTUTARI,0) ELSE ISNULL(NETTOPLAM,0) END) ELSE KDVLITOPLAM END),0),2)
WHERE FATID>@FATID AND KDVLITOPLAM IS NULL

