title: Compare two rows using a single cursor in SQL
body: <p>I have the following table</p>
  
  <pre><code>+-------+-------+----------+------+
  | icode | iname | icatcode | slno |
  +-------+-------+----------+------+
  |    10 | a     |       11 |    0 |
  |    20 | b     |       31 |    0 |
  |    30 | c     |       11 |    0 |
  |    40 | d     |       21 |    0 |
  |    50 | e     |       31 |    0 |
  |    60 | f     |       11 |    0 |
  |    70 | g     |       21 |    0 |
  |    80 | h     |       41 |    0 |
  +-------+-------+----------+------+
  </code></pre>
  
  <p>I need to update the <em>slno</em> column using a cursor. The o/p should be the following table ie., when the <em>icatcode</em> is same it should increment the <em>slno</em> and when <em>icatcode</em> changes it should set the <em>slno</em> to 1.</p>
  
  <pre><code>+-------+-------+----------+------+
  | icode | iname | icatcode | slno |
  +-------+-------+----------+------+
  |    10 | a     |       11 |    1 |
  |    30 | b     |       11 |    2 |
  |    60 | c     |       11 |    3 |
  |    70 | d     |       21 |    1 |
  |    40 | e     |       21 |    2 |
  |    50 | f     |       31 |    1 |
  |    20 | g     |       31 |    2 |
  |    80 | h     |       41 |    1 |
  +-------+-------+----------+------+
  </code></pre>
  
  <p>I have written the query for it</p>
  
  <pre><code>declare @icode int,@iccode int,@islno int,@inccode int
  
  set @islno=1
  
  declare cur2 cursor for select icode,iccode from im order by iccode
  
  open cur2
  
  fetch next from cur2 into @icode,@iccode
  
  while @@FETCH_STATUS=0
  
  begin
  
      update im  set slno=@islno where @icode=icode
      fetch next from cur2 into @icode,@inccode
      if @iccode&lt;&gt;@inccode
      begin
      set @islno=1
      end
      else
      begin
      set @islno=@islno+
      end
  
  end
  
  close cur2
  deallocate cur2
  </code></pre>
  
  <p>The above query results the following o/p</p>
  
  <pre><code>+-------+-------+----------+------+
  | icode | iname | icatcode | slno |
  +-------+-------+----------+------+
  |    10 | a     |       11 |    1 |
  |    20 | b     |       31 |    1 |
  |    30 | c     |       11 |    2 |
  |    40 | d     |       21 |    1 |
  |    50 | e     |       31 |    1 |
  |    60 | f     |       11 |    3 |
  |    70 | g     |       21 |    1 |
  |    80 | h     |       41 |    1 |
  +-------+-------+----------+------+
  </code></pre>
  
  <p>What changes do I need to do so that I will get the desired o/p? I need to do this  only by using cursors.</p>