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.
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.
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.
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.
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...
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