On a large sample set, this outperforms almost all other suggestions.Declare @mytable table(xval int, Gcode varchar(2), dord int, primary key (dord))insert into @mytable(gcode,dord)select 'a',100 union allselect 'a',200 union allselect 'a',300 union allselect 'b',400 union allselect 'b',500 union allselect 'c',600 union allselect 'd',700 Union allselect 'a',800 Union allselect 'a',900declare @gcode varchar(2), @xval intselect top 1 @xval = 1, @gcode = gcodefrom @mytableorder by dordupdate @mytableset @xval = xval = case when gcode <> @gcode then @xval + 1 else @xval end, @gcode = gcodeselect *from @mytable
Result from ProfilerCPU Reads Writes Duration 0 51 0 1
E 12°55'05.63"N 56°04'39.26"