SQL Server将自动增量主键添加到现有表 [英] SQL Server add auto increment primary key to existing table

查看:108
本文介绍了SQL Server将自动增量主键添加到现有表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为标题,我有一个现有表,该表已经填充了150000条记录。我添加了一个Id列(当前为空)。

As the title, I have an existing table which is already populated with 150000 records. I have added an Id column (which is currently null).

我假设我可以运行查询以用增量数字填充此列,然后将其设置为主键并打开自动递增功能。这是正确的进行方式吗?如果是这样,我该如何填写初始数字?

I'm assuming I can run a query to fill this column with incremental numbers, and then set as primary key and turn on auto increment. Is this the correct way to proceed? And if so, how do I fill the initial numbers?

推荐答案

否-您必须采用另一种方法:添加它一开始就是 INT IDENTITY -当您执行此操作时,它将被标识值填充:

No - you have to do it the other way around: add it right from the get go as INT IDENTITY - it will be filled with identity values when you do this:

ALTER TABLE dbo.YourTable
   ADD ID INT IDENTITY

然后可以将其设为主键:

and then you can make it the primary key:

ALTER TABLE dbo.YourTable
   ADD CONSTRAINT PK_YourTable
   PRIMARY KEY(ID)

,或者您更喜欢一步一步进行操作:

or if you prefer to do all in one step:

ALTER TABLE dbo.YourTable
   ADD ID INT IDENTITY
       CONSTRAINT PK_YourTable PRIMARY KEY CLUSTERED

这篇关于SQL Server将自动增量主键添加到现有表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆