UPDATE FATURA SET DOVIZKURU = 1 WHERE DOVIZKURU = 0 AND DOVIZKODU IN ('TL', 'TRL')
GO

UPDATE FATURA SET ODENEN = QODEME.ODEME
--select DOVIZKODU, turadı, odenen, ODENEN* DOVIZKURU, gtoplam, kurumtıpı, ODEME, * 
from FATURA INNER JOIN
(SELECT FATCOUNTER, SUM(VWMDS_CARIISLEM.DALACAK) ODEME FROM VWMDS_CARIISLEM (NOLOCK)  
 WHERE ISLTUR <> 'FATURA' GROUP BY FATCOUNTER 
 ) QODEME ON FATURA.FATID = QODEME.FATCOUNTER
WHERE TURADI IN (N'SATIŞ', N'SATIŞ İADE') AND ODENDI = 1 AND GTOPLAM > 0 and (DBO.PARAYUVARLA((GTOPLAM - ISNULL(KESINTI, 0)) / CASE WHEN DOVIZKURU = 0 THEN 1 ELSE DOVIZKURU END)) - ISNULL(ODENEN, 0) > 0.02 
AND NOT EXISTS (SELECT CARIISLID FROM VWMDS_CARIISLEM (NOLOCK) WHERE ISLTUR <> 'FATURA' AND FATCOUNTER = FATID AND DOVIZ <> DOVIZKODU) 
AND ISNULL(ODENEN, 0) <> QODEME.ODEME
--order by tarıh desc
GO

UPDATE FATURA SET ODENEN = QODEME.ODEME, ODENDI = 1
--select DOVIZKODU, turadı, odenen, ODENEN* DOVIZKURU, gtoplam, kurumtıpı, ODEME, * 
from FATURA INNER JOIN
(SELECT FATCOUNTER, SUM(VWMDS_CARIISLEM.DALACAK) ODEME FROM VWMDS_CARIISLEM (NOLOCK)  
 WHERE ISLTUR <> 'FATURA' GROUP BY FATCOUNTER 
 ) QODEME ON FATURA.FATID = QODEME.FATCOUNTER
WHERE TURADI IN (N'SATIŞ', N'SATIŞ İADE') AND ODENDI = 0 AND GTOPLAM > 0 and (DBO.PARAYUVARLA((GTOPLAM - ISNULL(KESINTI, 0)) / CASE WHEN DOVIZKURU = 0 THEN 1 ELSE DOVIZKURU END)) - ISNULL(QODEME.ODEME, 0) <= 0.01 
AND NOT EXISTS (SELECT CARIISLID FROM VWMDS_CARIISLEM (NOLOCK) WHERE ISLTUR <> 'FATURA' AND FATCOUNTER = FATID AND DOVIZ <> DOVIZKODU) 
AND KURUMTIPI <> 0
GO