I have a query below that works in SQL Server to select the difference between a value in one column and the value from another column, but two rows earlier in the source table. The source table has three columns (PK bigint, Pv float, Cash float).
When I use this query, what I get back is a series of single-row rowsets, rather than one big rowset. I can insert these one-by-one into a temp table then select out of that, but this means for large tables I end up with a big temp table as well as a long delay to the first record being returned.
Is there any way to spool the results of this query efficiently as a single row set?
declare @PK bigint
declare @Pv float
declare @Cash float
declare @Cash_minus_1 float
declare @Cash_minus_2 float
set @Cash_minus_1 = 0
set @Cash_minus_2 = 0
declare myCursor cursor fast_forward
for select PK, Pv, Cash from MyTable order by PK
for read only
open myCursor
fetch next from myCursor
into @PK, @Pv, @Cash
while @@FETCH_STATUS = 0
begin
select @PK, @Pv, @Cash, @Cash_minus_2
set @Cash_minus_2 = @Cash_minus_1
set @Cash_minus_1 = @Cash
fetch next from myCursor
into @PK, @Pv, @Cash
end
close myCursor
deallocate myCursor