sql中循環(huán)處理當(dāng)前行數(shù)據(jù)和上一行數(shù)據(jù)相加減
以下事例,使用游標(biāo)循環(huán)表#temptable中數(shù)據(jù),然后讓當(dāng)前行和上一行中的argument1 相加 存放到當(dāng)前行的 argument2 中,比較簡(jiǎn)單。
--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
問(wèn)一個(gè)問(wèn)題:
第一句fetch next from _cursor into @argument2 這句為什么不能放在while循環(huán)的第一行,刪除第二行呢?我記得自己當(dāng)時(shí)在這里出錯(cuò)了,呵呵。
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。