views:

26

answers:

3

I want to change the primary key value for one row in a table that has relations with other tables:

For example

Table Person { Id, Name, +50 fields }
Table Address { Id, City, +10 fields }
Table Person2Address { Id, PersonId, AddressId }

I want to change Person.Id and Person2Address.PersonId

I try something like:

BEGIN TRANSACTION    
  UPDATE Pers SET Id = NewId WHERE Id = OldId
  UPDATE Person2Address SET PersonId = NewId WHERE PersonId = OldId
COMMIT TRANSACTION

But of course it provides conflicts :)

How can I temporary suppress foreign key constraints or is there a better way to change Id for person?

+1  A: 

Your easiest bet for things like this is to use something like:

BEGIN TRANSACTION    
  UPDATE Pers SET tempId = NewId WHERE Id = OldId
  UPDATE Person2Address SET tempPersonId = NewId WHERE PersonId = OldId
COMMIT TRANSACTION

Then drop the Id and PersonId fields and rename the temp ones.

Aaron Harun
Thank you for the answer but it looks like @marc_s approach seems to be easier
Andrew Florko
+1  A: 

First off, changing the primary key value is never a good idea. Your main focus should be to try and avoid that by all means.

If you cannot eliminate the need to update the primary key value, then your best bet would be to define the foreign key relationship between those two tables to be using ON UPDATE CASCADE, so that any changes to the main table's primary key will be automatically cascaded down to the child table.

To do this, drop your existing foreign key relationship and then add:

 ALTER TABLE dbo.Person2Address
   ADD CONSTRAINT FK_Person2Address_Person
   FOREIGN KEY (PersonId) REFERENCES dbo.Person(Id)
     ON UPDATE CASCADE

That should then automatically update the Person2Address table's PersonId value if the Id on the person changes.

Now you should be able to just call

UPDATE dbo.Person SET Id = NewId WHERE Id = OldId

and that should be all there is!

marc_s
Badly tested code inserted {0000-0000-0000} guid value as PK so I want to change it. Thank you, I'll try
Andrew Florko
+1  A: 

You can drop FK constraints and recreate them when finished.

ALTER TABLE some_table DROP CONSTRAINT my_constraint

Check this article for creating and modifying constraints.

šljaker
Thank you for the article
Andrew Florko