Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control order of assignment for new identity column in SQL Server?

I have a table with CreateDate datetime field default(getdate()) that does not have any identity column.

I would like to add identity(1,1) field that would reflect same order of existing records as CreateDate field (order by would give same results). How can I do that?

I guess if I create clustered key on CreateDate field and then add identity column it will work (not sure if it's guaranteed), is there a good/better way?

I am interested in SQL Server 2005, but I guess the answer will be the same for SQL Server 2008, SQL Server 2000.

like image 711
alpav Avatar asked Mar 15 '10 19:03

alpav


People also ask

How do I manage the identity column in replication?

When Subscriber inserts are replicated back to the Publisher, identity columns must be managed to avoid assignment of the same identity value at both the Subscriber and Publisher. Replication can manage identity ranges automatically or you can choose to manually handle identity range management.

Do SQL inserts have to be in order?

If you are specifying the column names, the order doesn't matter. For example: INSERT INTO TABLE_NAME VALUES ('','','') // Here the values needs to be in order of columns present in your table. INSERT INTO TABLE_NAME (ID, NAME, EMAIL) VALUES ('','','')` // Here, ordering can be changed as per requirement.

How do you change the seed value of an identity column?

To change the original seed value and reseed any existing rows, drop the identity column and recreate it specifying the new seed value. When the table contains data, the identity numbers are added to the existing rows with the specified seed and increment values.


1 Answers

Following on from Remus' theoretical answer... you need to generate a list first with your ideal ordering

SELECT
    ID, CreateDate
INTO
    MyNewTable
FROM
    (
    SELECT
        CreateDate,
        ROW_NUMBER() OVER (ORDER BY CreateDate ASC) AS ID
    FROM
        MyTable
    ) foo

Then, the best solution is to use SSMS to add the IDENTITY property to MyNewTable. SSMS will generate a script that includes SET IDENTITY INSERT to preserve the order

Note: IDENTITY columns are just numbers that have no implicit meaning and nothing should be inferred by their alignment with the CreateDate after this exercise...

like image 188
gbn Avatar answered Sep 21 '22 17:09

gbn