如何将新标识列添加到SQL Server中的表?

时间:2010-09-13 08:22:45

标签: tsql sql-server-2008

我正在使用SQL Server 2008 Enterprise。我想将一个标识列(作为唯一聚簇索引和主键)添加到现有表。基于整数的自动增加1个标识列是可以的。任何解决方案?

BTW:我最困惑的是现有行,如何自动填写新的标识列数据?

提前谢谢, 乔治

3 个答案:

答案 0 :(得分:44)

你可以使用 -

alter table <mytable> add ident INT IDENTITY

这会将ident列添加到您的表中,并添加从1开始并递增1的数据。

添加聚集索引 -

CREATE CLUSTERED INDEX <indexName> on <mytable>(ident) 

答案 1 :(得分:0)

有一种方法,但不确定它是否可行。但请允许我向您保证,这是一种非常有效的方法。您可以创建具有标识列的表,并将整个数据插入该表中。从那里开始处理任何重复数据都是孩子的游戏。有两种方法可以将标识列添加到具有现有数据的表中:

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

作为参考,我找到了两篇文章: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/

答案 2 :(得分:0)

并非总是具有DBCC命令的权限。

解决方案2:

.ComboLBox.children()