Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreign Key fails to create

Tags:

I want a foreign key between 2 tables , so i try it like i always do. Now the issue i'm having is he fails to create , and by the looks of it it fails to create because there is already a key but there isnt.

- Unable to create relationship   'FK_tbl_Paramed_RegistratieBehandelingen_Users'.     The ALTER TABLE statement conflicted with the    FOREIGN KEY constraint "FK_tbl_Paramed_RegistratieBehandelingen_Users".    The conflict occurred in database "Nestor_Server",    table "dbo.Users", column 'UserID'. 

Ive checked if they have the same type , they do(bigint) so don't get why he won't create it

like image 938
Nicolas Pierre Avatar asked Jul 04 '12 07:07

Nicolas Pierre


People also ask

How do I fix foreign key constraint failure?

The error message itself showing there is a foreign key constraint error, which means you are deleting a parent table where the child table contains the Primary table identifier as a foreign key. To avoid this error, you need to delete child table records first and after that the parent table record.

What problems do foreign keys introduce?

Foreign key problems. Many database users encounter foreign key errors, often due to referential integrity problems. A foreign key might point to data that no longer exists, or the foreign key's data type doesn't match the primary key data type, eroding referential integrity.

Why can't I add a foreign key constraint?

The usual cause are generally a mismatch in the type of the column of the primary table and the foreign table. It can also be a mismatch in the Engine type of two tables i.e. MyISAM or InnoDB. Datatype both columns should have same datatype. int(11) on one table and smallint(5) on another will cause problem.

What is not true about foreign key?

Q 26 - Which of the following is not true about a FOREIGN KEY constraint? A - It is a referential integrity constraint. B - It establishes a relationship between a primary key or a unique key in the same table or a different table. C - A foreign key value cannot be null.


1 Answers

It is possible that you have records in RegistratieBehandelingen(Not sure about the table name) which is not present in Users Table.

select * from RegistratieBehandelingen a where UserID IS NULL or not exists (select 1 from Users b where b.UserID= a.UserID) 
like image 144
praveen Avatar answered Sep 21 '22 02:09

praveen