views:

27

answers:

2

Hi

I have the following table with 10 unique rows, BookingID is a FK containing a random number. The number doesn't need to be in sequence.

BookingID, Description
1000       Foo
3000       Bar
1500       Zoo

I need to insert an sequential index called ID which goes from 1..x

how do I do that in SQL Server 2005? I was thinking to write a cursor and x=x+1 but maybe there is a better way?

This is the result I want

Id, BookingID, Description
1   1000       Foo
2   3000       Bar
3   1500       Zoo
+4  A: 

This:

SELECT ROW_NUMBER() OVER(ORDER BY t.bookingid) AS id,
       t.bookingid,
       t.description
  FROM YOUR_TABLE t

...will produce:

id  bookingid   description
----------------------------
1   1000        Foo
2   3000        Bar
3   1500        Zoo

To update the existing id column, use:

WITH cte AS (
   SELECT t.id,
          ROW_NUMBER() OVER(ORDER BY t.bookingid) AS rank,
          t.bookingid,
          t.description
     FROM YOUR_TABLE t)
UPDATE cte
   SET id = rank
OMG Ponies
yes, an update statement to write the id value.
Makach
@omg ponies, yes, it exists and contains null values for each row, but I would like to populate the field with sequential number like you illustrated, but I cannot use identity on the field after the id rows are set.
Makach
@Makach: See update
OMG Ponies
Thank you! This is exactly what I wanted. 15000 rows migrated successfully.
Makach
A: 

BETTER ALTER THAT TABLE ADN ADD A IDENTITY COLUMN LIKE

ALTER TABLE TABLENAME ADD SRNO IDENTITY(1,1)

Vivek Iyer