Number Rows in a Table

From TekiWiki
Jump to: navigation, search

Say you have a Microsoft SQL Server table (MyTable) with a number column (say 15 digits, no decimals called SequenceNum), and you want this column to count the rows. In Oracle Database you would simply update the column with rownum:

update MyTable set SequenceNum = rownum

In SQL Server, we need to set up a counter and then increment it as we go:

declare @intCounter decimal(15,0)
select @intCounter = 0
update MyTable set @intCounter = SequenceNum = @intCounter + 1

Microsoft SQL Server