I want to add a column to an existing legacy database and write a procedure by which I can assign each record a different value. Something like adding a column and autogenerate the data for it.
Like, if I add a new column called "ID" (number) I want to then initialize a unique value to each of the records. So, my ID column will have records from say 1 to 1000
.
How do I do that?
9条答案
按热度按时间2w3rbyxf1#
This will depend on the database but for SQL Server, this could be achieved as follows:
mklgxw1f2#
It would help if you posted what SQL database you're using. For MySQL you probably want auto_increment:
Not sure if this applies the values retroactively though. If it doesn't you should just be able to iterate over your values with a stored procedure or in a simple program (as long as no one else is writing to the database) and set use the
LAST_INSERT_ID()
function to generate the id value.3phpmpom3#
for oracle you could do something like below
vx6bjr1n4#
And the Postgres equivalent (second line is mandatory only if you want "id" to be a key):
7y4bm7vi5#
Just using an ALTER TABLE should work. Add the column with the proper type and an IDENTITY flag and it should do the trick
Check out this MSDN article http://msdn.microsoft.com/en-us/library/aa275462(SQL.80).aspx on the ALTER TABLE syntax
yyyllmsg6#
for UNIQUEIDENTIFIER datatype in sql server try this
If you want to create primary key out of that column use this
fsi0uk1n7#
Depends on the database as each database has a different way to add sequence numbers. I would alter the table to add the column then write a db script in groovy/python/etc to read in the data and update the id with a sequence. Once the data has been set, I would add a sequence to the table that starts after the top number. Once the data has been set, set the primary keys correctly.
hujrc8aj8#
If you don't want your new column to be of type
IDENTITY
(auto-increment), or you want to be specific about the order in which your rows are numbered, you can add a column of typeINT NULL
and then populate it like this. In my example, the new column is called MyNewColumn and the existing primary key column for the table is called MyPrimaryKey.This works in SQL Sever 2005 and later, i.e. versions that support
ROW_NUMBER()
3qpi33ja9#
Make sure column name is Id.