开发者

Can I retrieve a value from a previous line using CURSORs of SQL?

I'm developing a query, where I need that a certain field of my current line be the res开发者_如何学Cult 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
;


I do believe FETCH PRIOR is available in SQLServer 2008....See this MS page

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜