代码之家  ›  专栏  ›  技术社区  ›  George2

如何在SQLServer中向表中添加新的标识列?

  •  20
  • George2  · 技术社区  · 16 年前

    我使用的是SQL Server 2008 Enterprise。我想向现有表中添加一个标识列(作为唯一聚集索引和主键)。基于整数的自动增加1个标识列是可以的。有什么解决办法吗?

    提前谢谢, 乔治

    2 回复  |  直到 16 年前
        1
  •  49
  •   Sachin Shanbhag    16 年前

    你可以用-

    alter table <mytable> add ident INT IDENTITY
    

    CREATE CLUSTERED INDEX <indexName> on <mytable>(ident) 
    
        2
  •  0
  •   NG.    14 年前

    Create a new table with identity, copy data to this new table then drop the existing table followed by renaming the temp table.
    
    Create a new column with identity & drop the existing column
    

    作为参考,我发现了2篇文章: http://blog.sqlauthority.com/2009/05/03/sql-server-add-or-remove-identity-property-on-column/ http://cavemansblog.wordpress.com/2009/04/02/sql-how-to-add-an-identity-column-to-a-table-with-data/

        3
  •  0
  •   Alexander Shapkin    7 年前

    并不总是对DBCC命令有权限。

    解决方案2:

    create table #tempTable1 (Column1 int)
    declare @new_seed varchar(20) = CAST((select max(ID) from SomeOtherTable) as varchar(20))
    exec (N'alter table #tempTable1 add ID int IDENTITY('+@new_seed+', 1)')
    
    推荐文章