Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Assume a table called Colors with fields <code>ID</code>, <code>Color</code>, and <code>ColorIndex</code> of types <code>int</code>, <code>varchar</code>, and <code>int</code> respectively. I also assume the OP means prev / after based on an ordering of the <code>ID</code> field in <code>asc</code> order.</p> <p>You could do this without a cursor, and use a while loop...but it definately isn't set based:</p> <pre><code>DECLARE @MyID int DECLARE @CurrentIndex int DECLARE @CurrentColor varchar(50) DECLARE @PreviousColor varchar(50) SET @CurrentIndex = (SELECT 0) SET @MyID = (SELECT TOP 1 ID FROM Colors ORDER BY ID ASC) SET @CurrentColor = (SELECT '') SET @PreviousColor = (SELECT Color FROM Colors WHERE ID = @MyID) WHILE (@MyID IS NOT NULL) BEGIN IF (@CurrentColor &lt;&gt; @PreviousColor) BEGIN SET @PreviousColor = (SELECT Color FROM Colors WHERE ID = @MyID) SET @CurrentIndex = (SELECT @CurrentIndex + 1) UPDATE Colors SET ColorIndex = @CurrentIndex WHERE ID = @MyID END ELSE BEGIN UPDATE Colors SET ColorIndex = @CurrentIndex WHERE ID = @MyID SET @PreviousColor = (SELECT Color FROM Colors WHERE ID = @MyID) END SET @MyID = (SELECT TOP 1 ID FROM Colors WHERE ID &gt; @MyID ORDER BY ID ASC) SET @CurrentColor = (SELECT Color FROM Colors WHERE ID = @MyID) END </code></pre> <p>The result after execution:</p> <p><img src="https://i.stack.imgur.com/HTiox.png" alt="enter image description here"></p> <p>Performance wasn't too shabby as long as ID and color are indexed. The plus side is it is a bit faster then using a regular old CURSOR and it's not as evil. Solution supports SQL 2000, 2005, and 2008 (being that you are using SQL 2000 which did not support CTEs).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload