Reputation: 53
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. 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 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? Or is there any other way for this kind of task ?
Upvotes: 1
Views: 1977
Reputation: 74197
You're going to need 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.
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.
Good Luck!
[I recommend a full backup before you start]
Upvotes: 1
Reputation: 346
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. 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.
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
Upvotes: 1