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:
- disable enforcing FK constraints temporarily (see here or here)
- update your PK
- update your FKs
- 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
- Open table in design mode
- Click Relationship button from top toolbar
- Select the required FK relations (one by one)
- Right Side - Expand INSERT or UPDATE Specification
- Change the UPDATE Rule to - Cascade
Close and Save, Done!
(Tried on SQL 2008)