views:

28

answers:

2

I'm developing a query, where I need that a certain field of my current line be the result of "the field of my current line" + "the same field of the previous line". (SQL Server 2008)

How can I do it by using cursors?

+4  A: 

Assign the previous line value to a variable:

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;
Remus Rusanu
Would a CTE not be a tad more elegant...?
gbn
@gbn: I'd like `LEAD` and `LAG` support, myself
OMG Ponies
@OMG Ponies: yep, forgot about those...
gbn
If you can do it in a set oriented with CTE, yes it would be more elegant. OP was specifically about `CURSOR` though. Besides, `CURSOR`s aren't quite the devil they're often painted to be...
Remus Rusanu
Thank you very much, I've just start to learning how cursor works, and your example really helped me! I thank all the other answers too!
Kira
@Kira: please note that the value of 'previous' will be undefined unless an explicit `ORDER BY` clause exists in the cursor's SELECT.
Remus Rusanu
A: 

Would this be an appropriate solution using the CTE?

WITH MyCTE AS
    (SELECT ROW_NUMBER() OVER (ORDER BY col1) AS Sequence, Col1, Col2
    FROM Table1)

SELECT c1.Sequence, c1.Col1 AS Prev_Co1,
    c2.Col1 AS Cur_Col1, c1.Col2 AS Prev_Col2, c2.Col2 AS Cur_Col2,
    COALESCE(c1.Col2, 0) + COALESCE(c2.Col2, 0) AS Sum_Col2
FROM MyCTE AS c1
LEFT OUTER JOIN MyCTE AS c2 ON c1.Sequence = c2.Sequence + 1
;
bobs
Sorry, but I don't know anything about CTEs... but soon I'll be starting to learning how this works. Thank you!
Kira