Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alter Table Add Column with Default value And FK, that Value no existing in FK Reference Data

This is My Tables :

Member : Id, ....

Product: Id, ....

My Member Table have some values none if them with Id = 0 and I don't want to add any member with Id = 0, So I try to run this Script:

ALTER TABLE [Product]
ADD [Member_Id] BIGINT  NOT NULL  DEFAULT(0),
CONSTRAINT [FK_Product_Member] FOREIGN KEY ([Member_Id]) REFERENCES [Member];

So There is an Error :

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Product_Member".

So I try this one:

SET IDENTITY_INSERT [Member] ON
INSERT INTO [Member] ([Id]) VALUES  (0);
SET IDENTITY_INSERT [Member] OFF

ALTER TABLE [Product]
ADD [Member_Id] BIGINT  NOT NULL  DEFAULT(0),
CONSTRAINT [FK_Product_Member] FOREIGN KEY ([Member_Id]) REFERENCES [Member];

DELETE FROM [Member] WHERE [Member].[Id] = 0;

Then The new Error is:

The DELETE statement conflicted with the REFERENCE constraint "FK_Product_Member".

If I try to create all Tables again, every thing will be OK of course with lost my Data so need to get backup, create tables and restore data. So Is there any way to alter Table with this situation? what is your suggestion?

like image 585
Saeid Avatar asked May 03 '12 06:05

Saeid


People also ask

What is the default value in all the rows for the new integer column added by Alter statement when no default value is specified )?

If not explicitly specified, the default value of a column is NULL. If you add a default to a new column, existing rows in the table gain the default value in the new column.

Can I add a foreign key constraint to an existing table with data?

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

What is FK referenced table?

A foreign key is a column or group of columns in a relational database table that provides a link between data in two tables. It acts as a cross-reference between tables because it references the primary key of another table, thereby establishing a link between them.


1 Answers

The only "value" that you can have in a referencing table, such that the foreign key constraint is not enforced, is NULL. Not 0, or any other magic value.

So the obvious solution is to allow NULLs:

ALTER TABLE [Product]
ADD [Member_Id] BIGINT  NULL,
CONSTRAINT [FK_Product_Member] FOREIGN KEY ([Member_Id]) REFERENCES [Member];
like image 68
Damien_The_Unbeliever Avatar answered Sep 28 '22 05:09

Damien_The_Unbeliever