SQL Server add auto increment primary key to existing table(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 向现有表添加自动增量主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQL Server 向现有表添加自动增量主键
基础教程推荐
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 在 SQL 中连接多个表 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 无法解决整理冲突 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
