this script should work on all cases, and should be quite efficient even on larger data sets. You can query intermediate temporary tables to see what I'm doing. Table #accumulated_amount_with_salary on each row has all the data it needs to calculate the distribution amount.
Edit: since i assumed REC is always 0 at the beginning, my query was not working correctly. I've updated the query by recalculating the EMI (substracting REC amount)
--drop table #accumulated_amount;
select a.emi-a.rec as emi, a.duedt, a.rec, a.acno, coalesce(sum(b.emi-b.rec),0) as emi_accumulated
into #accumulated_amount
from tbl_emi a
left join tbl_emi b on a.acno = b.acno and b.duedt < a.duedt
group by a.emi, a.duedt, a.rec, a.acno;
--drop table #accumulated_amount_with_salary;
select a.*, s.trnamt as salary_amt
into #accumulated_amount_with_salary
from #accumulated_amount a
inner join slary s on a.acno = s.acno;
update #accumulated_amount_with_salary
set rec = rec + case
when salary_amt < emi_accumulated then 0
when (salary_amt - emi_accumulated) < emi then salary_amt - emi_accumulated
else emi
end
update t
set rec = a.rec
from tbl_emi t
inner join #accumulated_amount_with_salary a on t.acno = a.acno and t.duedt = a.duedt;