Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL update a table with a foreign key

Tags:

sql

I have a categories table, which one of the fields serves as the foreign key for a sub-categories table. One field that serves as part of the primary key for each table is the language id. I need to update these in both tables. Basically, wherever the language id = x in both tables, I need to set it to y.

When I try to do an update on either table, I get a 'The UPDATE statement conflicted with the REFERENCE constraint..' which refers to the foreign key constraint.

How can I update the language field on both of these tables?

like image 260
derek Avatar asked Apr 19 '10 19:04

derek


People also ask

How do you update a table that has a foreign key?

Login to the SQL Server using SQL Server Management Studio, Navigate to the Keys folder in the child table. Right click on the Keys folder and select New Foreign Key. Edit table and columns specification by clicking … as shown in the below image. Select the parent table and the primary key column in the parent table.

Does foreign key auto update?

Save this answer. Show activity on this post. No the foreign key is not updated automatically. You need to update the foreign key in the tables in which it is referenced by yourself else it would result in referential integrity exception.

Can you add foreign key with ALTER TABLE?

We can add a FOREIGN KEY constraint to a column of an existing MySQL table with the help of ALTER TABLE statement.

Can we update foreign key in a table MySQL?

Here is how you would do that: ALTER TABLE my_table ADD FOREIGN KEY (key) REFERENCES other_table(id) ON DELETE SET NULL; And that's it!! That's how you change a foreign key constraint in MySQL!


2 Answers

Use this, no need to remove and add as well.

ALTER TABLE Table_Name
    NOCHECK CONSTRAINT FoerignKey_Name

--update query here

ALTER TABLE Table_Name
    CHECK CONSTRAINT FoerignKey_Name

For more info MSDN link : https://docs.microsoft.com/en-us/sql/relational-databases/tables/disable-foreign-key-constraints-with-insert-and-update-statements?view=sql-server-ver15

like image 64
Mehsaan1719 Avatar answered Nov 02 '22 10:11

Mehsaan1719


I'm always leery about disabling constraints, and you really don't want to do that if this is a common operation.

An admittedly ugly alternative is to: - Create a row in the parent table, based on the row to be updated but containing the new foreign key value - Update all child rows where the foreign key contains the old value with the new value. - Delete the now-unused parent key row

This is awkward for any number of obvious reasons, and may not be suitable to your implementation, but it maintains referential integrity within the database.

like image 31
Philip Kelley Avatar answered Nov 02 '22 08:11

Philip Kelley