0

嗨,我有一个现有的表,女巫有一列 ExamQuestionsAnswersDocumentId。该列设置为主键,大约有 60000 行数据。

列的类型是 int,每行都有一个唯一的 id。这些行是从另一个表、另一个 db 传输的,我们需要在新表中保留准确的 id 值。

这是我到目前为止所做的:

CREATE TABLE ExamQuestionsAnswersDocuments(
ExamQuestionsAnswersDocumentId int NOT NULL,
RootStorageId int NOT NULL,
StorageFileName varchar(200),
OriginalFileName varchar(200),
Title varchar(200),
Deletion_Date datetime,
Creation_Date datetime,
Modification_Date datetime,
RowVersion int,
CreatedBy int,
ModifiedBy int,
DeletedBy int,
CONSTRAINT FK_ExamQuestionsAnswersDocuments_FileShareRootStorage 
FOREIGN KEY (RootStorageId) REFERENCES FileShareRootStorage(FileShareRootStorageId)

)

之后,我运行了此脚本以将数据添加到新表中:

 INSERT INTO [LocalServerB].[dbo].[ExamQuestionsAnswersDocuments] (ExamQuestionsAnswersDocumentId , RootStorageId , StorageFileName , OriginalFileName , Title , Deletion_Date , Creation_Date , Modification_Date , [RowVersion] , CreatedBy , ModifiedBy , DeletedBy)
SELECT d.DocumentId     as ExamQuestionsAnswersDocumentId,
       2                as RootStorageId,
       d.RealName       as StorageFileName,
       d.FileName       as OriginalFileName,
       d.Title          as Title,
       d.Deletion_Date  as Deletion_Date,
       d.Creation_Date  as Creation_Date,
       d.Modification_Date as Modification_Date,
       d.[RowVersion]          as [RowVersion],
       d.CreatedBy             as CreatedBy,
       d.ModifiedBy            as ModifiedBy,
       d.DeletedBy             as DeletedBy
FROM [LocalServerA].[dbo].[Sync_Exams] as e 
JOIN [LocalServerA].[dbo].[Documents]  as d ON d.DocumentId = e.QuestionsDocumentID OR
                                     d.DocumentID = e.AnswersDocumentID

到目前为止一切顺利,我必须将 ExamQuestionsAnswersDocumentId 设置为主键:

ALTER TABLE ExamQuestionsAnswersDocuments
ADD CONSTRAINT PK_ExamQuestionsAnswersDocumentId PRIMARY KEY CLUSTERED (ExamQuestionsAnswersDocumentId)
GO

现在作为最后一部分,我需要在每次添加新行时将列设置为自动递增。使用 SSMS 很容易,但我需要在实际数据库上运行它的脚本。

我在网上找到的所有解决方案都说这是不可能的,该列将被重新生成,但必须有一种方法能够将其设置为 IDENTITY AUTO INCREMENT 而无需重新生成列。

我尝试使用 SSMS 进行此操作,即使添加了一些新行,也没有重新生成任何内容。有趣的是,它会从找到的最高 ID 继续递增。

有谁知道如何将列设置为自动增量标识?

4

1 回答 1

2

创建表时将其设置为身份,然后使用

 set Identity_Insert ExamQuestionsAnswersDocuments on

在插入数据之前,然后

 set Identity_Insert ExamQuestionsAnswersDocuments off

然后。例如:

CREATE TABLE ExamQuestionsAnswersDocuments(
    ExamQuestionsAnswersDocumentId int NOT NULL identity(1,1),
    RootStorageID int,
    ...
)

set identity_insert ExamQuestionsAnswersDocuments on

insert ExamQuestionsAnswersDocuments(ExamQuestionsAnswersDocumentId, RootStorageID, ...) 
Select ...

set identity_insert ExamQuestionsAnswersDocuments off
于 2013-09-20T11:26:30.420 回答