2 years ago
#42886

Ludovic Aubert
mass update of primary keys along with foreign keys
Here is a sample
CREATE TABLE A(ida int PRIMARY KEY);
CREATE TABLE B(idb int PRIMARY KEY, ida int);
ALTER TABLE B
ADD CONSTRAINT FK_B_ida FOREIGN KEY (ida) REFERENCES A(ida);
INSERT INTO A (ida) VALUES (1);
INSERT INTO B (idb, ida) VALUES (1, 1);
BEGIN TRANSACTION
UPDATE A
SET ida = ida + 1000;
UPDATE B
SET ida = ida + 1000;
COMMIT TRANSACTION;
When running the part between BEGIN TRANSACTION
and COMMIT TRANSACTION
(all 4 lines), I get an error
Msg 547 - UPDATE instruction conflicts with FOREIGN KEY constraint "FK_B_ida"
In the context of a data migration project (merging 2 dbs with the same schema), I need to mass update primary keys (to avoid collisions) and make sure foreign keys follow.
What is the recommended way to do this?
I was thinking, I could offset keys during copy, but that might make the copy script complex (difficult to avoid listing column names)
sql-server
foreign-keys
primary-key
database-migration
0 Answers
Your Answer