Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The INSERT statement conflicted with the FOREIGN KEY SAME TABLE constraint

I have created table Employee

Create table Employee
(   
    FName varchar(20) Not Null,
    LName varchar(20) Not Null,
    SSN int Not Null,
    BDate Datetime,
    Address varchar(50),
    Sex char(1),
    Salary money,
    Super_SSN int,
    Primary Key(SSN),
    Foreign Key(Super_SSN) references Employee(SSN)
)

When i try to insert first row to ,

insert into Employee(FName,LName,SSN,BDate,Address,Sex,Salary,Super_SSN)
values('John','Smith',12345,'1965-01-09','Houston,TX','M',30000,33344) 

I am getting the error like..

Error:

The INSERT statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK_Employee_Employee". The conflict occurred in database "Company", table "dbo.Employee", column 'SSN'.

like image 265
SanjayDVG Avatar asked Jul 17 '14 19:07

SanjayDVG


People also ask

What is foreign key same table constraint?

The FOREIGN KEY SAME TABLE error can occur when you have a table that has an attribute which is a foreign key that refers to itself. The error will occur if the attribute has a value that is not present in the table as a primary key.

How insert value in table which contains foreign key?

If you are inserting data into a dependent table with foreign keys: Each non-null value you insert into a foreign key column must be equal to some value in the corresponding parent key of the parent table. If any column in the foreign key is null, the entire foreign key is considered null.

What is foreign key constraint error?

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.


1 Answers

You need to first INSERT record for SSN '33344' with Super_SSN value as NULL.

INSERT INTO  Employee(FName,LName,SSN,BDate,Address,Sex,Salary,Super_SSN)
VALUES (<FName>,<LName>,'33344',<BDate>,<Address>,<Sex>,<Salary>,NULL)

After that insert

INSERT INTO Employee (FName,LName,SSN,BDate,Address,Sex,Salary,Super_SSN)
VALUES ('John','Smith',12345,'1965-01-09','Houston,TX','M',30000,33344)

If SSN '33344' have any Super_SSN, update the SSN value (this record should be available in table).

like image 194
Jesuraja Avatar answered Sep 28 '22 02:09

Jesuraja