title: How to get Latest value of row in Cursor result set in SQL
body: <p>I am using Cursor for some operation on same table which I used in Select statement of Cursor as below,</p>
  
  <pre><code>CREATE TABLE #nsn (ID INT IDENTITY(1,1)
  ,Val1 Varchar(MAx)
  ,Val2 Varchar(MAx)
  )
  
  INSERT INTO #nsn(Val1,VAl2) select 'A1','A2'
  INSERT INTO #nsn(Val1,VAl2) select 'B1','B2'
  INSERT INTO #nsn(Val1,VAl2) select 'C1','C2'
  INSERT INTO #nsn(Val1,VAl2) select 'D1','D2'
  INSERT INTO #nsn(Val1,VAl2) select 'E1','F2'
  
  SELECT * From #nsn
  ID  Val1    VAl2
  1|  A1  |   A2
  2|  B1  |   B2
  3|  C1  |   C2
  4|  D1  |   D2
  5|  E1  |   F2
  </code></pre>
  
  <p>use cursor to update Val2 column,</p>
  
  <pre><code>DECLARE @ID INT 
          ,@Val1 Varchar(MAx)
          ,@Val2 Varchar(MAx)
  
  DECLARE cursor_Latest CURSOR
  FOR SELECT  ID,Val1,Val2
      FROM    #nsn 
      ORder by 1 asc
  OPEN cursor_Latest
  FETCH NEXT FROM cursor_Latest INTO  @ID , @Val1 ,@Val2
  WHILE (@@FETCH_STATUS &lt;&gt; -1)
  BEGIN
      UPDATE #nsn
      SET Val2 = Val2 +'-'+ @Val1 +'-'+@Val2
      WHERE ID = @ID+1
  
      FETCH NEXT FROM cursor_Latest INTO  @ID , @Val1 ,@Val2
  END
  close cursor_Latest
  DEALLOCATE cursor_Latest
  </code></pre>
  
  <p>and its result is </p>
  
  <pre><code>SELECT * From #nsn
  ID  Val1    VAl2
  1|  A1  |   A2
  2|  B1  |   B2-A1-A2
  3|  C1  |   C2-B1-B2
  4|  D1  |   D2-C1-C2
  5|  E1  |   F2-D1-D2
  </code></pre>
  
  <p>But I am expecting result as below,</p>
  
  <pre><code>ID  Val1    VAl2
  1|  A1  |   A2
  2|  B1  |   B2-A1-A2
  3|  C1  |   C2-B1-B2-A1-A2
  4|  D1  |   D2-C1-C2-B1-B2-A1-A2
  5|  E1  |   F2-D1-D2-C1-C2-B1-B2-A1-A2
  </code></pre>
  
  <p>So is there any thing wrong in this code? or 
  does Cursor has any record store thing because it is not getting latest updated values of new row.</p>
  
  <p>Advance Thanks for Help..</p>