Solved

Updating using current row number

Posted on 2004-08-10
4
1,951 Views
Last Modified: 2008-03-17
I'm trying to update a field for a series of records to contain sequential numbers, like a fix to remove gaps in the numbers.

So that, if I can return the following table:

ID  |  Value
87  |    5
89  |    11
95  |    18
98  |    23

I want to be able to do a single UPDATE query, to make:

ID  |  Value
87  |    1
89  |    2
95  |    3
98  |    4

I would prefer an answer that is the same in both MSSQL and MySQL, but an answer for either one of them will earn the points
0
Comment
Question by:neur0maniak
4 Comments
 
LVL 142

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 200 total points
ID: 11761439
In MSSQL Server, I would perform this operation like this:

CREATE TABLE TEMP ( ID INT )
INSERT INTO TABLE TEMP SELECT ID FROM yourtable
CREATE CLUSTERED INDEX CIDX_ID ON TABLE TEMP ( ID )
ALTER TABLE TEMP ADD VALUE INT IDENTITY (1,1)
UPDATE yourtable SET VALUE = TEMP.VALUE
FROM yourtable JOIN TEMP on TEMP.ID = yourtable.ID
DROP TABLE TEMP

I don't know about how I would do this in MySQL, but I assume it won't work that way...

Actually, if you use a cursor, this can be done quite easily (pseudo-code):
open the cursor (SELECT ID, VALUE FROM yourtable ORDER BY ID ASC )
@value = 0
for each row
   @Value = @Value+1
   update current row SET VALUE = @Value


That's it. Of course, not a single UPDATE. You might think about an update like the current:
UPDATE yourtable SET Value = (select count(*) from Yourtable ti WHERE ti.ID <= yourtable.ID )

It can work in MSSQL (not sure in MySQL), but performance is really bad...

Cheers
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Creating and Managing Databases with phpMyAdmin in cPanel.
Using SQL Scripts we can save all the SQL queries as files that we use very frequently on our database later point of time. This is one of the feature present under SQL Workshop in Oracle Application Express.
Video by: Steve
Using examples as well as descriptions, step through each of the common simple join types, explaining differences in syntax, differences in expected outputs and showing how the queries run along with the actual outputs based upon a simple set of dem…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now