将新主键插入已包含数据的表中

问题描述 投票:0回答:2

我有一个包含数百万条记录的表,需要添加新的 int 字段“Id”作为自动增量的主键。现在我已经设法对具有合理少量数据的表进行处理,但某些表保存了数百万条记录并抛出超时错误。数据库是Azure SQL

'MyTable(dbo)' table
- Unable to modify table.  
Execution Timeout Expired.  The timeout period elapsed prior to completion of the operation or the 
server is not responding.
The statement has been terminated.
sql-server azure-sql-server
2个回答
1
投票

我做了一个示例代码,也许你可以参考:

CREATE TABLE dbo.doc_exz (column_a INT not null, column_b INT) ;
GO
INSERT INTO dbo.doc_exz VALUES (7,7) ;
INSERT INTO dbo.doc_exz VALUES (7,7) ;
INSERT INTO dbo.doc_exz VALUES (7,7) ;
INSERT INTO dbo.doc_exz VALUES (7,7) ;
GO

ALTER TABLE dbo.doc_exz ADD id int IDENTITY(1,1) not null 
GO

ALTER TABLE doc_exz ADD PRIMARY KEY (id)
GO        
SELECT * FROM dbo.doc_exz ;
GO

DROP TABLE dbo.doc_exz ;
GO

查询的输出:

如果仍然出现超时错误。你可以按照@Larnu的建议:

  1. 创建新版本的表
  2. 将现有数据插入其中
  3. 然后删除旧表并重命名新表。

对于大量数据,可以使用BULK INSERT


0
投票

在尝试添加具有自动增量值的主键列时,我遇到了相同的超时问题。在 SSMS 中修复了它,无需编写任何查询。

以下是步骤:

  1. 右键单击表格。转到“设计”并添加 Id 列 enter image description here

  2. 右键单击该列并选择“设置主键” enter image description here

  3. 在身份规范中,将身份识别设置为“是”并根据您的要求发送增量和种子。 enter image description here

  4. 在工具/选项/设计器中,根据您的数据量将“事务超时时间”增加到 300 或更多。

enter image description here

  1. 保存更改。

现在您应该能够看到带有自动增量值的 Id 列。

© www.soinside.com 2019 - 2024. All rights reserved.