Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use for loop in SQL server

Tags:

sql

sql-server

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?

like image 226
User M Avatar asked Oct 10 '12 09:10

User M


2 Answers

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.

  • The WITH statement is similar to a sub query
  • In that, the ROW_NUMBER() creates the sequential ids that you want
  • The outer query then updates the column (Although it refers to the sub-query, the real table does actually get updated)
like image 136
MatBailie Avatar answered Sep 22 '22 02:09

MatBailie


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

like image 42
Tim Schmelter Avatar answered Sep 22 '22 02:09

Tim Schmelter