sql中循環(huán)處理當前行數(shù)據(jù)和上一行數(shù)據(jù)相加減
發(fā)布日期:2021-12-27 05:10 | 文章來源:源碼中國
以下事例,使用游標循環(huán)表#temptable中數(shù)據(jù),然后讓當前行和上一行中的argument1 相加 存放到當前行的 argument2 中,比較簡單。
--drop table #temptable
create table #temptable
(
argument1 int,
argument2 int,
argument3 datetime
)
declare @rowcount int,@argument1 int,@argument2 nvarchar(50),@argument3 datetime
set @rowcount=1
set @argument1=1
set @argument2=0
set @argument3=GETDATE()
while(@rowcount<100)
begin
insert into #temptable(argument1,argument2,argument3)
values(@argument1,@argument2,@argument3)
set @argument1=@argument1 + datepart(day,@argument3)
set @argument3=@argument3-1
set @rowcount = @rowcount + 1
end
--select * from #temptable
declare @lastargument2 int
set @lastargument2=0
set @argument2=0
declare _cursor cursor for(select argument1 from #temptable)
open _cursor;
fetch next from _cursor into @argument2
while @@fetch_status = 0
begin
update #temptable
set argument2=@argument2+@lastargument2
where current of _cursor
set @lastargument2=@argument2
fetch next from _cursor into @argument2
end
close _cursor
deallocate _cursor
--select * from #temptable
問一個問題:
第一句fetch next from _cursor into @argument2 這句為什么不能放在while循環(huán)的第一行,刪除第二行呢?我記得自己當時在這里出錯了,呵呵。
版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
相關(guān)文章
關(guān)注官方微信