Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server: change primary key with related rows

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?

like image 858
Andrew Florko Avatar asked Jul 05 '10 06:07

Andrew Florko


People also ask

Can you modify primary key in SQL?

You can modify a primary key in SQL Server by using SQL Server Management Studio or Transact-SQL. You can modify the primary key of a table by changing the column order, index name, clustered option, or fill factor.

Can two relatives have the same primary key?

The column or columns defined as the primary key ensure uniqueness in the table; no two rows can have the same key. The primary key of one table may also help to identify records in other tables, and be part of the second table's primary key.

Can multiple rows have the same primary key?

The whole idea of a primary key is to have a unique identifier for each row, so you can not do that. However, if you want a way of grouping rows, you can either add a group column to your table, or create a table for the grouping.


1 Answers

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!

like image 84
marc_s Avatar answered Oct 11 '22 19:10

marc_s