我可以使用SQL的CURSOR检索上一行的值吗?

Kir*_*ira 2 sql-server cursor

我正在开发一个查询,我需要当前行的某个字段是"当前行的字段"+"前一行的相同字段"的结果.(SQL Server 2008)

如何使用游标来做到这一点?

Rem*_*anu 5

将前一行值分配给变量:

declare @previosvalue varchar(100) = null;
declare @currentvalue varchar(100);

declare crs cursor for select value from table;
open crs;

fetch next from crs into @currentvalue;
while @@fetch_status = 0
begin
   -- process here. On first row, @previousvalue is NULL
   -- as it should be, since there is no 'previous' of first

   select ... from sometable
   where somecondition = @currentvalue
   and othercondition = @previousvalue;

   set @previousvalue = @currentvalue;
   fetch next from crs into @currentvalue;
end

close crs;
deallocate crs;
Run Code Online (Sandbox Code Playgroud)

  • @gbn:我自己也喜欢"LEAD"和"LAG"支持 (2认同)