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?
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?
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;
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
;