将现有列设置为自动递增

时间:2013-09-20 11:24:27

标签: sql sql-server

我有一个现有的表有一个专栏ExamQuestionsAnswersDocumentId.This列被设置为主键,有大约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继续增加。

有谁知道如何将列设置为AUTO INCREMENT标识?

1 个答案:

答案 0 :(得分: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