简体   繁体   English

需要删除并重新创建主键上具有identity(1:1)的SQL表

[英]Need to drop and recreate SQL table with identity(1:1) on primary key

I have a table with some million records. 我有一张桌子,上面有几百万条记录。 This table has 1:N relation to some other tables and this other tables have also some 1: N relations. 该表与其他一些表具有1:N关系,而该其他表也具有一些1:N关系。 Primary key on this table has auto increment i:1 , this primary key is used in those linked tables so i have to retain these id's 该表上的主键具有自动增量i:1,此主键用于那些链接表中,因此我必须保留这些ID的

I need to recreate the table with some changes. 我需要重新创建表并进行一些更改。 I can recreate the tables but i need some suggestions on How to retain the auto-generated ID's and populate them so it wont break the relationship with other tables? 我可以重新创建表,但是我需要一些有关如何保留自动生成的ID并填充它们的建议,以免破坏与其他表的关系? Or is there any other way for this kind of task ? 还是有其他方法可以完成此类任务?

Why can't you make changes to the table without re-creating it? 为什么不重新创建表就不能对其进行更改? Example below add a column to #TableA and then changes its datatype. 下面的示例在#TableA中添加一列,然后更改其数据类型。 Alternatively, you can copy the data to a different table and then insert it back to re-created table by enabling identity insert SET IDENTITY_INSERT ON and then inserting identity value. 或者,您可以将数据复制到另一个表中,然后通过启用标识插入SET IDENTITY_INSERT ON然后插入标识值,将其重新插入到重新创建的表中。

  create table #TableA
    (
        RecordId int identity(1, 1) primary key not null,
        Name nvarchar(128) not null
    )

    alter table #TableA
    add Dob datetime null


    alter table #TableA
    alter column Dob date null

Example of Identity insert: 身份插入示例:

SET IDENTITY_INSERT #TableA ON
INSERT INTO #TableA (RecordId, Name, Dob) Values (1, 'some name', '02/04/2014')
SET IDENTITY_INSERT #TableA OFF

You're going to need set identity_insert [on|off] . 您将需要set identity_insert [on|off] That will allow inserts and bulk loads of identity columns. 这将允许插入和批量装载身份列。 After the inserts are done, you'll need to run dbcc checkident with the reseed option to reset the identity counter. 在插入完成后,你需要运行dbcc checkidentreseed选项复位身份计数器。

Don't forget to need to drop or disable any related constraints (foreign keys, etc.) and triggers that might cause problems during your remodelling. 不要忘记需要删除或禁用任何相关的约束(外键等)和触发器,这些约束可能会在重塑期间引起问题。 Or to recreate or reenable them when your done. 或者在完成后重新创建或重新启用它们。

After you're all done, you'll probably want to run alter table foo check constraint ... to verify that you haven't broken anything. 完成所有操作后,您可能需要运行alter table foo check constraint ...以验证您没有破坏任何内容。

Good Luck! 祝好运!

[I recommend a full backup before you start] [我建议您在开始前进行完整备份]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM