SQL Server update primary key that's also a foreign key in two tables

Are your relationships using

ON UPDATE CASCADE 

If they are then changing the key in the primary table will update the foreign keys.

e.g.

ALTER TABLE Books 
ADD CONSTRAINT fk_author 
FOREIGN KEY (AuthorID) 
REFERENCES Authors (AuthorID) ON UPDATE CASCADE 

You may:

  1. disable enforcing FK constraints temporarily (see here or here)
  2. update your PK
  3. update your FKs
  4. enable back enforcing FK constraints

do it all within a transaction and make sure that if transaction fails, you roll it back properly and still enforce the FK constraints back.

But... why do you need to change a PK? I hope this is an action that is executed rarely (legacy data import or something like that).


If you would like to set the Cascade rule graphically then Set Cascade Rule on SQL Management Studio

  1. Open table in design mode
  2. Click Relationship button from top toolbar
  3. Select the required FK relations (one by one)
  4. Right Side - Expand INSERT or UPDATE Specification
  5. Change the UPDATE Rule to - Cascade

Close and Save, Done!

(Tried on SQL 2008)

Tags:

Sql Server