--同一张表内、利用变化的上一行数据动态地修改下一行数据(示例Demo)

/**//*
CREATETABLEAccount(
[Month][datetime]NOTNULLPrmaryKey,
[PlanFare][money]NULL,
[PutoutFare][money]NULL,
[PlanPreFare][money]NULL,
[PutoutPreFare][money]NULL
)--Account表生成脚本
*/
selectidentity(int,1,1)as[id],*into#fromaccountorderby[month]asc
CREATETABLE#Temp(
[id][int]NOTNULL,
[Month][datetime]NOTNULL,
[PlanFare][money]NULL,
[PutoutFare][money]NULL,
[PlanPreFare][money]NULL,
[PutoutPreFare][money]NULL
)
declare@idint
declaremcursorforselect[id]from#orderby[id]asc
openm
fetchnextfromminto@id
while(@@fetch_status=0)
begin
insertinto#Temp([id],[Month],PlanFare,PutoutFare,PlanPreFare,PutoutPreFare)
select[id],[Month],PlanFare,PutoutFare,PlanPreFare,PutoutPreFarefrom#where[id]=@id
UPDATE#
SET#.PlanPreFare=(a.PlanFare-a.putoutFare)+(a.PlanPreFare-a.putoutPreFare)
FROM#TempASa
WHERE#.[id]=a.[id]+1
--前行作依据,后行来修改(此次的后行,变成下次的前行,依此循环,直至表中的行遍历结束)
truncatetable#Temp
fetchnextfromminto@id
end
closem
deallocatem

UPDATEAccount
SETAccount.PlanPreFare=a.PlanPreFare
FROM#ASa
WHEREAccount.[Month]=a.[Month]

droptable#
droptable#Temp

本文介绍了一种在SQL中利用前一行数据动态更新后一行数据的方法。通过创建临时表并使用游标遍历的方式,实现了根据当前行的数据调整下一行预估费用的功能。
2404

被折叠的 条评论
为什么被折叠?



