Technical Article

Update a table column with a sequence number v2.0

,

In response to Sachinvaishnav's search for a better way to insert a sequence number column in the same table, I bring you a cursor free Sql server 2005 example that utilizes the new ROW_NUMBER() OVER(ORDER BY) Function available in 2005

/*
==================================================================
This query helps you to insert a sequence number in the table.
It is useful when you have decided to add the sequence type of column quite late. 
===================================================================
*/
-- Make a temp table and load it with a thousand rows of redundant data
DECLARE @tableA AS TABLE 
(
SeqId Numeric(10)
, FirstName Varchar(50)
, LastName Varchar(50)
)

DECLARE @mStart INT
SET @mStart = 0
WHILE @mStart < 1000
BEGIN
INSERT INTO @tableA VALUES (NULL, 'abc', 'xyz')

SET @mStart = @mStart + 1
END
-- BEFORE Values
-- SELECT * FROM @TableA


-- NOW LET THE FUN BEGIN --
DECLARE @Counter INT
SET @Counter = 1

DECLARE @RowCount INT
SET @RowCount = (  SELECT Count(*) FROM @tableA)

WHILE @Counter <= @RowCount
BEGIN
UPDATE TOP(1) @TableA
SET SeqID = 
(
SELECT RowID FROM
(
SELECT ROW_NUMBER() OVER(ORDER By SeqID) AS RowID 
FROM @tableA
)  AS T1 WHERE RowID = @counter
) WHERE SeqID IS NULL
SET @Counter = @Counter + 1
END

SELECT * FROM @tableA

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating