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ò)了,呵呵。
相關(guān)文章
SQLServer中NEWID()函數(shù)用于生成一個(gè)唯一的標(biāo)識(shí)符的方法實(shí)踐
NEWID函數(shù)用于生成一個(gè)唯一的標(biāo)識(shí)符,本文主要介紹了SQLServer中NEWID()函數(shù)用于生成一個(gè)唯一的標(biāo)識(shí)符的方法實(shí)踐,具有一定的參考價(jià)值,感興趣的可以了解一下2024-08-08
Sql學(xué)習(xí)第二天——SQL DML與CTE概述
關(guān)于DML即數(shù)據(jù)操縱語(yǔ)言;關(guān)于CTE即公用表表達(dá)式,接下來(lái)為大家介紹下CTE使用的地方以及優(yōu)點(diǎn)同時(shí)提供一個(gè)簡(jiǎn)單的CTE例題,感興趣的各位可以參考下哈2013-03-03
ASP.NET下向SQLServer2008導(dǎo)入文件實(shí)例操作方法
在Microsoft SQL Server2008以后的版本中,將刪除image數(shù)據(jù)類(lèi)型。在新的開(kāi)發(fā)工作中將不適用此數(shù)據(jù)類(lèi)型,并打算修改當(dāng)前使用此數(shù)據(jù)類(lèi)型的應(yīng)用程序,改用varbinary(max)數(shù)據(jù)類(lèi)型。2010-09-09
SQLServer導(dǎo)入數(shù)據(jù)圖文方法
有時(shí)需要將別的數(shù)據(jù)庫(kù)的內(nèi)容,導(dǎo)入到當(dāng)前數(shù)據(jù)庫(kù)中,就需要導(dǎo)入數(shù)據(jù)即可。下面是詳細(xì)的圖文方法。2010-07-07
SQL Server中實(shí)現(xiàn)數(shù)據(jù)庫(kù)的自定義視圖
在SQL Server的數(shù)據(jù)處理和分析中,視圖(View)是一種虛擬的表,其內(nèi)容由SQL查詢(xún)定義,自定義視圖允許用戶(hù)根據(jù)需要?jiǎng)?chuàng)建個(gè)性化的數(shù)據(jù)展示,本文將詳細(xì)介紹如何在SQL Server中實(shí)現(xiàn)數(shù)據(jù)庫(kù)的自定義視圖,需要的朋友可以參考下2024-07-07
自動(dòng)化收集SQLSERVER診斷信息的工具選擇及使用介紹
相信很多人都遇到過(guò)當(dāng)SQLSERVER出現(xiàn)問(wèn)題的時(shí)候,如果想解決的話一般需要你收集一些系統(tǒng)信息和SQLSERVER診斷信息;接下來(lái)將介紹下工具的選擇及使用,感興趣的你可不要錯(cuò)過(guò)了哈,或許本文的知識(shí)點(diǎn)可以幫助到你2013-02-02

