Add a column to existing table and uniquely number them on MS SQL Server

前端 未结 8 1254
暖寄归人
暖寄归人 2020-12-04 08:16

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 ad

相关标签:
8条回答
  • 2020-12-04 08:32

    for oracle you could do something like below

    alter table mytable add (myfield integer);
    
    update mytable set myfield = rownum;
    
    0 讨论(0)
  • 2020-12-04 08:37

    It would help if you posted what SQL database you're using. For MySQL you probably want auto_increment:

    ALTER TABLE tableName ADD id MEDIUMINT NOT NULL AUTO_INCREMENT KEY

    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.

    0 讨论(0)
  • 2020-12-04 08:39

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

    UPDATE MyTable
    SET MyTable.MyNewColumn = AutoTable.AutoNum
    FROM
    (
        SELECT MyPrimaryKey, 
        ROW_NUMBER() OVER (ORDER BY SomeColumn, SomeOtherColumn) AS AutoNum
        FROM MyTable 
    ) AutoTable
    WHERE MyTable.MyPrimaryKey = AutoTable.MyPrimaryKey  
    

    This works in SQL Sever 2005 and later, i.e. versions that support ROW_NUMBER()

    0 讨论(0)
  • 2020-12-04 08:41

    for UNIQUEIDENTIFIER datatype in sql server try this

    Alter table table_name
    add ID UNIQUEIDENTIFIER not null unique default(newid())
    

    If you want to create primary key out of that column use this

    ALTER TABLE table_name
    ADD CONSTRAINT PK_name PRIMARY KEY (ID);
    
    0 讨论(0)
  • 2020-12-04 08:43

    And the Postgres equivalent (second line is mandatory only if you want "id" to be a key):

    ALTER TABLE tableName ADD id SERIAL;
    ALTER TABLE tableName ADD PRIMARY KEY (id);
    
    0 讨论(0)
  • 2020-12-04 08:43

    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

    0 讨论(0)
提交回复
热议问题