我正在开发一个查询,我需要当前行的某个字段是"当前行的字段"+"前一行的相同字段"的结果.(SQL Server 2008)
如何使用游标来做到这一点?
将前一行值分配给变量:
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)