且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL Server 将自动增量主键添加到现有表

更新时间:2023-02-04 22:53:15

不 - 你必须反其道而行之:从一开始就将其添加为 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