I have to update multiple rows(29) in a table in SQL server 2005.
SELECT * from tblState ORDER BY StateCode ASC.
In this table there's a integer column which I need to assign numbers starting from 1 to 29. For e.g.
BEFORE
A 3
B 6
C 2
D 1
AFTER
A 1
B 2
C 3
D 4
How can I update each row with a ascending sequential number efficiently?
WITH
sequenced_data AS
(
SELECT
ROW_NUMBER() OVER (ORDER BY StateCode ASC) AS sequence_id,
*
FROM
tblState
)
UPDATE
sequenced_data
SET
integer_column = sequence_id
As you are asking for a loop I guess you may not understand this code.
As such, I strongly recommend you create a dummy table to play with this, both to understand that how it works, and to ensure it does what you want/expect.
WITH
statement is similar to a sub query ROW_NUMBER()
creates the sequential ids that you want You should avoid loops in SQL whenever possible. SQL Server is heavily optimized towards set-based operations.
In this case you can use a CTE
with ROW_NUMBER
function:
WITH CTE AS
(
SELECT StateCode, IntColumn
, RN = ROW_NUMBER() OVER (ORDER BY StateCode ASC)
FROM dbo.tblState
)
UPDATE CTE SET IntColumn = RN;
Bad Habits to Kick : Thinking a WHILE loop isn't a CURSOR
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With