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

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

问题描述:

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

I am using SQL Server 2008 Enterprise. I want to add an identity column (as unique clustered index and primary key) to an existing table. Integer based auto-increasing by 1 identity column is ok. Any solutions?

顺便说一句:我最困惑的是对于现有的行,如何自动填充新的标识列数据?

BTW: my most confusion is for existing rows, how to automatically fill-in new identity column data?

提前致谢,乔治

你可以使用-

alter table <mytable> add ident INT IDENTITY

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

This adds ident column to your table and adds data starting from 1 and incrementing by 1.

添加聚集索引 -

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