پس برای مثال، اول من تابع رو میسازم:
create function dbo.Calc(@Radif int, @Bedehkar money, @Bestankar money)
returns money
as
begin
declare @PrevRecord as int
declare @RetVal money
select @PrevRecord=max(radif) from dbo.test where radif<@radif
if @PrevRecord is null
begin
set @RetVal=@Bestankar-@Bedehkar
end
else
begin
declare @PrevMandeh money
select @PrevMandeh=Mandeh from dbo.test where radif=@PrevRecord
set @RetVal=@Bestankar-@Bedehkar+@PrevMandeh
end
return @RetVal
end
بعد جدول رو (باز برای مثال):
create table test(
Radif int,
Bedehkar money,
Bestankar money,
Mandeh as dbo.Calc(Radif, Bedehkar, Bestankar))
insert test values(1, 1000,0)
insert test values(2, 0,1000)
insert test values(3, 0, 2000)
و برای بهینه کردن سرعت تابع، این ایندکس رو نیاز داریم:
create index ix1 on test(radif)
حالا نتیجه:
select * from test
فقط در مورد فیلد Radif دقت کنید که ممکنه ردیف رو شما به شکل دیگه ای کنترل کرده باشین. در صورت نیاز، تابع رو ویرایش کنین تا با ساختار جدول شما مطابقت داشته باشه.
موفق باشید